"""
GT-LMS System Graphical Interface Implementation
This module provides PyQt6-based graphical user interface
"""

try:
    from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
                                QHBoxLayout, QLabel, QLineEdit, QPushButton,
                                QTextEdit, QListWidget, QTabWidget, QMessageBox,
                                QFormLayout, QGridLayout, QGroupBox, QComboBox,
                                QTableWidget, QTableWidgetItem, QHeaderView,
                                QDialog, QDialogButtonBox, QCheckBox, QMainWindow,
                                QInputDialog)
    from PyQt6.QtCore import Qt, pyqtSignal
    from PyQt6.QtGui import QFont, QPixmap, QAction
    import datetime
    PYQT6_AVAILABLE = True
    print("PyQt6 successfully imported. GUI features enabled.")
except ImportError as e:
    PYQT6_AVAILABLE = False
    print(f"PyQt6 not available. GUI features will be disabled. Error: {e}")

# Try to import matplotlib for data visualization
try:
    import matplotlib
    matplotlib.use('Qt5Agg')  # Use Qt5 backend
    from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
    from matplotlib.figure import Figure
    import matplotlib.pyplot as plt
    MATPLOTLIB_AVAILABLE = True
except ImportError:
    MATPLOTLIB_AVAILABLE = False
    print("Matplotlib not available. Data visualization features will be disabled.")

import sys
from typing import Optional
from models.user import UserRole

if PYQT6_AVAILABLE:
    # Create chart class for embedding matplotlib charts in PyQt6
    if MATPLOTLIB_AVAILABLE:
        class GradeChart(FigureCanvas):
            """Grade chart class"""
            
            def __init__(self, parent=None, width=5, height=4, dpi=100):
                self.fig = Figure(figsize=(width, height), dpi=dpi)
                super().__init__(self.fig)
                self.setParent(parent)
                
                # Create chart
                self.axes = self.fig.add_subplot(111)
                self.axes.set_title('Grade Distribution')
                self.axes.set_xlabel('Course')
                self.axes.set_ylabel('Grade')
                
            def plot_grades(self, courses, grades):
                """Plot grade chart"""
                self.axes.clear()
                
                # Create bar chart
                x_pos = range(len(courses))
                self.axes.bar(x_pos, grades, align='center', alpha=0.7)
                
                # Set x-axis labels
                self.axes.set_xticks(x_pos)
                self.axes.set_xticklabels(courses, rotation=45, ha='right')
                
                # Set y-axis range
                self.axes.set_ylim(0, 100)
                
                # Add grid
                self.axes.grid(True, linestyle='--', alpha=0.7)
                
                # Set title and labels
                self.axes.set_title('Grade Distribution')
                self.axes.set_xlabel('Course')
                self.axes.set_ylabel('Grade')
                
                # Refresh chart
                self.draw()
                
            def plot_grade_distribution(self, grades):
                """Plot grade distribution histogram"""
                self.axes.clear()
                
                # Create histogram
                self.axes.hist(grades, bins=10, edgecolor='black', alpha=0.7)
                
                # Set title and labels
                self.axes.set_title('Grade Distribution Histogram')
                self.axes.set_xlabel('Grade Range')
                self.axes.set_ylabel('Frequency')
                
                # Add grid
                self.axes.grid(True, linestyle='--', alpha=0.7)
                
                # Refresh chart
                self.draw()

if PYQT6_AVAILABLE:
    class LoginWindow(QMainWindow):
        """Login window class"""

        login_successful = pyqtSignal(str, str)  # email, password

        def __init__(self, lms_system=None):
            super().__init__()
            self.lms_system = lms_system
            self.init_ui()

        def init_ui(self):
            """Initialize user interface"""
            self.setWindowTitle("GT-LMS Learning Management System - Login")
            self.setGeometry(300, 300, 400, 300)

            # Create central widget
            central_widget = QWidget()
            self.setCentralWidget(central_widget)

            # Create main layout
            main_layout = QVBoxLayout()
            central_widget.setLayout(main_layout)

            # Title
            title_label = QLabel("GT-LMS Learning Management System")
            title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
            title_font = QFont()
            title_font.setPointSize(16)
            title_font.setBold(True)
            title_label.setFont(title_font)
            main_layout.addWidget(title_label)

            # Login form group
            form_group = QGroupBox("User Login")
            form_layout = QFormLayout()

            # Email input
            self.email_input = QLineEdit()
            self.email_input.setPlaceholderText("Please enter email address")
            form_layout.addRow("Email:", self.email_input)

            # Password input
            self.password_input = QLineEdit()
            self.password_input.setEchoMode(QLineEdit.EchoMode.Password)
            self.password_input.setPlaceholderText("Please enter password")
            form_layout.addRow("Password:", self.password_input)

            form_group.setLayout(form_layout)
            main_layout.addWidget(form_group)

            # Button layout
            button_layout = QHBoxLayout()

            # Login button
            login_button = QPushButton("Login")
            login_button.clicked.connect(self.handle_login)
            button_layout.addWidget(login_button)

            # Register button
            register_button = QPushButton("Register New User")
            register_button.clicked.connect(self.handle_register)
            button_layout.addWidget(register_button)

            # Exit button
            quit_button = QPushButton("Exit")
            quit_button.clicked.connect(self.close)
            button_layout.addWidget(quit_button)

            main_layout.addLayout(button_layout)

            # Set focus to email input
            self.email_input.setFocus()

            # Set enter key for login
            self.email_input.returnPressed.connect(self.handle_login)
            self.password_input.returnPressed.connect(self.handle_login)

        def handle_login(self):
            """Handle login event"""
            email = self.email_input.text().strip()
            password = self.password_input.text()

            if not email or not password:
                QMessageBox.warning(self, "Login Failed", "Please enter email and password")
                return

            # Send login success signal
            self.login_successful.emit(email, password)

        def handle_register(self):
            """Handle registration event"""
            try:
                # Create registration dialog
                register_dialog = RegisterDialog(self, self.lms_system)
                
                # Show registration dialog
                if register_dialog.exec() == QDialog.DialogCode.Accepted:
                    # Registration successful, can choose to auto-login
                    reply = QMessageBox.question(
                        self, 
                        "Registration Successful", 
                        "User registration successful! Login now?",
                        QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                        QMessageBox.StandardButton.Yes
                    )
                    
                    if reply == QMessageBox.StandardButton.Yes:
                        # Get email and password filled during registration
                        email = register_dialog.email_input.text().strip()
                        password = register_dialog.password_input.text()
                        
                        # Auto-fill login form
                        self.email_input.setText(email)
                        self.password_input.setText(password)
                        
                        # Auto-trigger login
                        self.handle_login()
                        
            except Exception as e:
                QMessageBox.critical(self, "Error", f"Error opening registration interface:\n{e}")
                print(f"[GUI] Error opening registration interface: {type(e).__name__}: {e}")

    class RegisterDialog(QDialog):
        """Registration dialog class"""
        
        def __init__(self, parent=None, lms_system=None):
            super().__init__(parent)
            self.lms_system = lms_system
            self.init_ui()
        
        def init_ui(self):
            """Initialize registration interface"""
            self.setWindowTitle("User Registration")
            self.setGeometry(350, 350, 500, 400)
            
            # Create main layout
            layout = QVBoxLayout()
            
            # Title
            title_label = QLabel("User Registration")
            title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
            title_font = QFont()
            title_font.setPointSize(16)
            title_font.setBold(True)
            title_label.setFont(title_font)
            layout.addWidget(title_label)
            
            # Registration form group
            form_group = QGroupBox("Registration Information")
            form_layout = QFormLayout()
            
            # User type selection
            self.user_type_combo = QComboBox()
            self.user_type_combo.addItems(["student", "teacher"])
            self.user_type_combo.setCurrentText("student")
            form_layout.addRow("User Type:", self.user_type_combo)
            
            # Student ID/Employee ID input
            self.user_id_input = QLineEdit()
            self.user_id_input.setPlaceholderText("Please enter student ID or employee ID")
            form_layout.addRow("Student ID/Employee ID:", self.user_id_input)
            
            # Name input
            self.name_input = QLineEdit()
            self.name_input.setPlaceholderText("Please enter name")
            form_layout.addRow("Name:", self.name_input)
            
            # Email input
            self.email_input = QLineEdit()
            self.email_input.setPlaceholderText("Please enter email address")
            form_layout.addRow("Email:", self.email_input)
            
            # Password input
            self.password_input = QLineEdit()
            self.password_input.setEchoMode(QLineEdit.EchoMode.Password)
            self.password_input.setPlaceholderText("Please enter password (at least 6 characters)")
            form_layout.addRow("Password:", self.password_input)
            
            # Confirm password input
            self.confirm_password_input = QLineEdit()
            self.confirm_password_input.setEchoMode(QLineEdit.EchoMode.Password)
            self.confirm_password_input.setPlaceholderText("Please enter password again")
            form_layout.addRow("Confirm Password:", self.confirm_password_input)
            
            form_group.setLayout(form_layout)
            layout.addWidget(form_group)
            
            # Button layout
            button_layout = QHBoxLayout()
            
            # Register button
            register_button = QPushButton("Register")
            register_button.clicked.connect(self.handle_register)
            button_layout.addWidget(register_button)
            
            # Cancel button
            cancel_button = QPushButton("Cancel")
            cancel_button.clicked.connect(self.reject)
            button_layout.addWidget(cancel_button)
            
            layout.addLayout(button_layout)
            
            self.setLayout(layout)
            
            # Set focus to user ID input
            self.user_id_input.setFocus()
            
            # Set Enter key for registration
            self.user_id_input.returnPressed.connect(self.handle_register)
            self.name_input.returnPressed.connect(self.handle_register)
            self.email_input.returnPressed.connect(self.handle_register)
            self.password_input.returnPressed.connect(self.handle_register)
            self.confirm_password_input.returnPressed.connect(self.handle_register)
        
        def validate_inputs(self):
            """Validate input data"""
            user_id = self.user_id_input.text().strip()
            name = self.name_input.text().strip()
            email = self.email_input.text().strip()
            password = self.password_input.text()
            confirm_password = self.confirm_password_input.text()
            
            # Check required fields
            if not all([user_id, name, email, password]):
                QMessageBox.warning(self, "Input Error", "All fields must be filled")
                return False
            
            # Check email format
            if "@" not in email or "." not in email:
                QMessageBox.warning(self, "Input Error", "Please enter a valid email address")
                return False
            
            # Check password length
            if len(password) < 6:
                QMessageBox.warning(self, "Input Error", "Password must be at least 6 characters")
                return False
            
            # Check password confirmation
            if password != confirm_password:
                QMessageBox.warning(self, "Input Error", "Passwords do not match")
                return False
            
            return True
        
        def handle_register(self):
            """Handle registration event"""
            if not self.validate_inputs():
                return
            
            user_type = self.user_type_combo.currentText()
            user_id = self.user_id_input.text().strip()
            name = self.name_input.text().strip()
            email = self.email_input.text().strip()
            password = self.password_input.text()
            
            try:
                # Prepare user data
                user_data = {
                    'user_id': user_id,
                    'name': name,
                    'email': email,
                    'password': password,
                    'user_type': user_type
                }
                
                # Create user
                if self.lms_system and self.lms_system.user_manager:
                    result = self.lms_system.user_manager.create_user(user_type, user_data)
                    
                    if result:
                        QMessageBox.information(self, "Registration Successful", "User registration successful!")
                        self.accept()  # Close dialog and return success
                    else:
                        QMessageBox.warning(self, "Registration Failed", "User registration failed, user ID or email may already exist")
                else:
                    QMessageBox.critical(self, "System Error", "User management system unavailable")
                    
            except Exception as e:
                QMessageBox.critical(self, "Registration Error", f"Error occurred during registration:\n{e}")
                print(f"[GUI] Error occurred during user registration: {type(e).__name__}: {e}")
    
    class StudentMainWindow(QMainWindow):
        """Student main window class"""

        def __init__(self, user_email: str, user=None, lms_system=None):
            super().__init__()
            self.user_email = user_email
            self.user = user
            self.lms_system = lms_system
            self.init_ui()

        def init_ui(self):
            """Initialize user interface"""
            self.setWindowTitle(f"GT-LMS Learning Management System (Student) - {self.user_email}")
            self.setGeometry(200, 200, 800, 600)

            # Create menu bar
            self.create_menu_bar()

            # Create central widget
            central_widget = QWidget()
            self.setCentralWidget(central_widget)

            # Create main layout
            main_layout = QVBoxLayout()
            central_widget.setLayout(main_layout)

            # Create tab widget
            self.tab_widget = QTabWidget()
            main_layout.addWidget(self.tab_widget)

            # Add various tabs
            self.create_dashboard_tab()
            self.create_courses_tab()
            self.create_assignments_tab()
            self.create_grades_tab()

            # Create status bar
            self.statusBar().showMessage(f"Welcome, {self.user_email}")

        def create_menu_bar(self):
            """Create menu bar"""
            menubar = self.menuBar()
            
            # File menu
            file_menu = menubar.addMenu('File')
            
            # Logout action
            logout_action = QAction('Logout', self)
            logout_action.setShortcut('Ctrl+L')
            logout_action.triggered.connect(self.logout)
            file_menu.addAction(logout_action)
            
            # Exit action
            exit_action = QAction('Exit', self)
            exit_action.setShortcut('Ctrl+Q')
            exit_action.triggered.connect(self.close)
            file_menu.addAction(exit_action)
            
            # Help menu
            help_menu = menubar.addMenu('Help')
            about_action = QAction('About', self)
            about_action.triggered.connect(self.show_about)
            help_menu.addAction(about_action)

        def logout(self):
            """Logout function"""
            print(f"[GUI] Student {self.user_email} requests logout")
            try:
                # Execute logout
                if self.lms_system and self.lms_system.auth_system:
                    self.lms_system.auth_system.logout()
                    print(f"[GUI] Student {self.user_email} logout successful")
                
                # Close current window
                self.close()
                
                # Re-display login window
                if hasattr(self, 'parent_gui') and self.parent_gui:
                    self.parent_gui.show_login_window()
                else:
                    # If no parent_gui, create new login window
                    from PyQt6.QtWidgets import QApplication
                    app = QApplication.instance()
                    if app:
                        login_window = LoginWindow()
                        login_window.show()
                
            except Exception as e:
                print(f"[GUI] Error occurred during student logout: {type(e).__name__}: {e}")
                QMessageBox.critical(self, "Logout Error", f"Error during logout:\n{e}")

        def show_about(self):
            """Show about dialog"""
            QMessageBox.about(self, "About", "GT-LMS Learning Management System\nVersion 1.0\n\nA comprehensive learning management system.")

        def create_dashboard_tab(self):
            """Create dashboard tab"""
            dashboard_widget = QWidget()
            layout = QVBoxLayout()

            # Welcome message
            welcome_label = QLabel(f"Welcome to GT-LMS Learning Management System, {self.user_email}!")
            welcome_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
            welcome_font = QFont()
            welcome_font.setPointSize(14)
            welcome_font.setBold(True)
            welcome_label.setFont(welcome_font)
            layout.addWidget(welcome_label)

            # System information
            info_text = QTextEdit()
            info_text.setReadOnly(True)
            info_text.setText("""
    System Features Overview:

    • Course Management - Browse and manage courses
    • Assignment System - View and submit assignments
    • Grade Inquiry - View personal grade records
    • Progress Tracking - Monitor learning progress

    Please use the tabs above to navigate to different function modules.
            """)
            layout.addWidget(info_text)

            dashboard_widget.setLayout(layout)
            self.tab_widget.addTab(dashboard_widget, "Dashboard")

        def create_courses_tab(self):
            """Create courses tab"""
            courses_widget = QWidget()
            layout = QVBoxLayout()

            # Course table
            self.courses_table = QTableWidget()
            self.courses_table.setColumnCount(4)
            self.courses_table.setHorizontalHeaderLabels(["Course Name", "Teacher", "Credits", "Status"])
            self.courses_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
            layout.addWidget(self.courses_table)

            # Button layout
            button_layout = QHBoxLayout()
            refresh_button = QPushButton("Refresh")
            enroll_button = QPushButton("Enroll")
            drop_button = QPushButton("Drop")

            button_layout.addWidget(refresh_button)
            button_layout.addStretch()
            button_layout.addWidget(enroll_button)
            button_layout.addWidget(drop_button)

            layout.addLayout(button_layout)
            courses_widget.setLayout(layout)
            self.tab_widget.addTab(courses_widget, "Courses")
            
            # Connect button signals
            refresh_button.clicked.connect(self.refresh_courses)
            enroll_button.clicked.connect(self.enroll_course)
            drop_button.clicked.connect(self.drop_course)

        def create_assignments_tab(self):
            """Create assignments tab"""
            assignments_widget = QWidget()
            layout = QVBoxLayout()

            # Assignment list
            self.assignments_list = QListWidget()
            layout.addWidget(self.assignments_list)

            # Assignment details
            details_group = QGroupBox("Assignment Details")
            details_layout = QVBoxLayout()

            self.assignment_details = QTextEdit()
            self.assignment_details.setReadOnly(True)
            details_layout.addWidget(self.assignment_details)

            # Submit button
            submit_button = QPushButton("Submit Assignment")
            details_layout.addWidget(submit_button)

            details_group.setLayout(details_layout)
            layout.addWidget(details_group)

            assignments_widget.setLayout(layout)
            self.tab_widget.addTab(assignments_widget, "Assignments")
            
            # Connect button signals
            submit_button.clicked.connect(self.submit_assignment)
            self.assignments_list.itemClicked.connect(self.show_assignment_details)
            
            # Refresh assignments when tab is selected
            self.tab_widget.currentChanged.connect(self.on_tab_changed)

        def create_grades_tab(self):
            """Create grades tab"""
            grades_widget = QWidget()
            layout = QVBoxLayout()

            # Grade table
            self.grades_table = QTableWidget()
            self.grades_table.setColumnCount(5)
            self.grades_table.setHorizontalHeaderLabels(["Course", "Assignment", "Grade", "Full Score", "Percentage"])
            self.grades_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
            layout.addWidget(self.grades_table)

            # Grade statistics
            stats_group = QGroupBox("Grade Statistics")
            stats_layout = QHBoxLayout()

            self.gpa_label = QLabel("GPA: 0.0")
            self.average_label = QLabel("Average: 0.0%")

            stats_layout.addWidget(self.gpa_label)
            stats_layout.addWidget(self.average_label)
            stats_layout.addStretch()

            stats_group.setLayout(stats_layout)
            layout.addWidget(stats_group)
            
            # Data visualization section
            if MATPLOTLIB_AVAILABLE:
                # Create chart container
                chart_group = QGroupBox("Grade Visualization")
                chart_layout = QVBoxLayout()
                
                # Create chart switch buttons
                button_layout = QHBoxLayout()
                bar_chart_button = QPushButton("Bar Chart")
                histogram_button = QPushButton("Distribution Chart")
                refresh_chart_button = QPushButton("Refresh Chart")
                
                button_layout.addWidget(bar_chart_button)
                button_layout.addWidget(histogram_button)
                button_layout.addWidget(refresh_chart_button)
                button_layout.addStretch()
                
                chart_layout.addLayout(button_layout)
                
                # Create chart
                self.grade_chart = GradeChart(grades_widget, width=5, height=4, dpi=100)
                chart_layout.addWidget(self.grade_chart)
                
                # Connect button signals
                bar_chart_button.clicked.connect(self.show_bar_chart)
                histogram_button.clicked.connect(self.show_histogram)
                refresh_chart_button.clicked.connect(self.refresh_chart)
                
                chart_group.setLayout(chart_layout)
                layout.addWidget(chart_group)
                
                # Add sample data
                self.sample_courses = ["Math", "Physics", "Chemistry", "English", "Computer Science"]
                self.sample_grades = [85, 78, 92, 88, 95]
                
                # Initially show bar chart
                self.show_bar_chart()
            else:
                # If matplotlib is unavailable, show prompt information
                no_chart_label = QLabel("Data visualization feature unavailable, please install matplotlib library")
                no_chart_label.setStyleSheet("color: red; font-style: italic;")
                layout.addWidget(no_chart_label)

            grades_widget.setLayout(layout)
            self.tab_widget.addTab(grades_widget, "Grades")
            
        def show_bar_chart(self):
            """Show grade bar chart"""
            if MATPLOTLIB_AVAILABLE and hasattr(self, 'grade_chart'):
                self.grade_chart.plot_grades(self.sample_courses, self.sample_grades)
                
        def show_histogram(self):
            """Show grade distribution histogram"""
            if MATPLOTLIB_AVAILABLE and hasattr(self, 'grade_chart'):
                self.grade_chart.plot_grade_distribution(self.sample_grades)
                
        def refresh_chart(self):
            """Refresh chart data"""
            if MATPLOTLIB_AVAILABLE and hasattr(self, 'grade_chart'):
                # Here you can get actual data from database
                # Now using random data simulation
                import random
                self.sample_grades = [random.randint(60, 100) for _ in range(len(self.sample_courses))]
                self.show_bar_chart()

        def refresh_courses(self):
            """Refresh student courses"""
            try:
                if not self.lms_system or not self.lms_system.course_manager:
                    QMessageBox.warning(self, "Warning", "Course manager not available")
                    return
                
                student = self.lms_system.user_manager.get_user_by_email(self.user_email)
                if not student:
                    QMessageBox.warning(self, "Warning", "Student not found")
                    return
                
                # Get student's enrolled courses
                enrolled_courses = self.lms_system.enrollment_manager.get_student_courses(student.user_id)
                
                # Get all available courses
                all_courses = self.lms_system.course_manager.get_all_courses()
                
                # Update courses table
                self.courses_table.setRowCount(len(enrolled_courses))
                for row, course in enumerate(enrolled_courses):
                    self.courses_table.setItem(row, 0, QTableWidgetItem(course.name))
                    
                    # Get teacher name
                    teacher = self.lms_system.user_manager.get_user_by_id(course.teacher_id)
                    teacher_name = teacher.name if teacher else "Unknown"
                    self.courses_table.setItem(row, 1, QTableWidgetItem(teacher_name))
                    
                    self.courses_table.setItem(row, 2, QTableWidgetItem(str(course.credits)))
                    self.courses_table.setItem(row, 3, QTableWidgetItem("Enrolled"))
                
                print(f"[GUI] Student {self.user_email} refreshed courses: {len(enrolled_courses)} courses found")
                
            except Exception as e:
                print(f"[GUI] Error refreshing student courses: {type(e).__name__}: {e}")
                QMessageBox.critical(self, "Error", f"Failed to refresh courses:\n{e}")

        def enroll_course(self):
            """Enroll in a course"""
            try:
                if not self.lms_system or not self.lms_system.course_manager:
                    QMessageBox.warning(self, "Warning", "Course manager not available")
                    return
                
                student = self.lms_system.user_manager.get_user_by_email(self.user_email)
                if not student:
                    QMessageBox.warning(self, "Warning", "Student not found")
                    return
                
                # Get available courses (not already enrolled)
                enrolled_courses = self.lms_system.enrollment_manager.get_student_courses(student.user_id)
                enrolled_course_ids = [course.course_id for course in enrolled_courses]
                all_courses = self.lms_system.course_manager.get_all_courses()
                available_courses = [course for course in all_courses if course.course_id not in enrolled_course_ids]
                
                if not available_courses:
                    QMessageBox.information(self, "Information", "No courses available for enrollment")
                    return
                
                # Create course selection dialog
                course_names = [f"{course.name} (ID: {course.course_id})" for course in available_courses]
                course_name, ok = QInputDialog.getItem(self, "Enroll Course", "Select a course to enroll:", course_names, 0, False)
                
                if ok and course_name:
                    # Extract course ID from the selected item
                    course_id = course_name.split("ID: ")[1].rstrip(")")
                    
                    # Enroll in the course
                    success = self.lms_system.enrollment_manager.create_enrollment(student.user_id, course_id)
                    
                    if success:
                        QMessageBox.information(self, "Success", "Successfully enrolled in course!")
                        self.refresh_courses()  # Refresh the course list
                        print(f"[GUI] Student {self.user_email} enrolled in course {course_id}")
                    else:
                        QMessageBox.warning(self, "Warning", "Failed to enroll in course. Course may be full or you may already be enrolled.")
                
            except Exception as e:
                print(f"[GUI] Error enrolling in course: {type(e).__name__}: {e}")
                QMessageBox.critical(self, "Error", f"Failed to enroll in course:\n{e}")

        def drop_course(self):
            """Drop a course"""
            try:
                if not self.lms_system or not self.lms_system.course_manager:
                    QMessageBox.warning(self, "Warning", "Course manager not available")
                    return
                
                student = self.lms_system.user_manager.get_user_by_email(self.user_email)
                if not student:
                    QMessageBox.warning(self, "Warning", "Student not found")
                    return
                
                # Get enrolled courses
                enrolled_courses = self.lms_system.enrollment_manager.get_student_courses(student.user_id)
                
                if not enrolled_courses:
                    QMessageBox.information(self, "Information", "You are not enrolled in any courses")
                    return
                
                # Create course selection dialog
                course_names = [f"{course.name} (ID: {course.course_id})" for course in enrolled_courses]
                course_name, ok = QInputDialog.getItem(self, "Drop Course", "Select a course to drop:", course_names, 0, False)
                
                if ok and course_name:
                    # Extract course ID from the selected item
                    course_id = course_name.split("ID: ")[1].rstrip(")")
                    
                    # Confirm drop
                    reply = QMessageBox.question(self, "Confirm Drop", f"Are you sure you want to drop {course_name}?\n\nThis action cannot be undone.",
                                               QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
                    
                    if reply == QMessageBox.StandardButton.Yes:
                        # Drop the course
                        # First find the enrollment ID for this student and course
                        student_enrollments = self.lms_system.enrollment_manager.get_student_enrollments(student.user_id)
                        enrollment_to_drop = None
                        
                        for enrollment in student_enrollments:
                            if enrollment.course_id == course_id and enrollment.status == "active":
                                enrollment_to_drop = enrollment
                                break
                        
                        if enrollment_to_drop:
                            success = self.lms_system.enrollment_manager.drop_enrollment(enrollment_to_drop.enrollment_id)
                            
                            if success:
                                QMessageBox.information(self, "Success", "Successfully dropped course!")
                                self.refresh_courses()  # Refresh the course list
                                print(f"[GUI] Student {self.user_email} dropped course {course_id}")
                            else:
                                QMessageBox.warning(self, "Warning", "Failed to drop course.")
                        else:
                            QMessageBox.warning(self, "Warning", "Enrollment not found.")
                
            except Exception as e:
                print(f"[GUI] Error dropping course: {type(e).__name__}: {e}")
                QMessageBox.critical(self, "Error", f"Failed to drop course:\n{e}")

        def refresh_assignments(self):
            """Refresh student assignments"""
            try:
                if not self.lms_system or not self.lms_system.assignment_manager:
                    QMessageBox.warning(self, "Warning", "Assignment manager not available")
                    return
                
                student = self.lms_system.user_manager.get_user_by_email(self.user_email)
                if not student:
                    QMessageBox.warning(self, "Warning", "Student not found")
                    return
                
                # Get student's enrolled courses
                enrolled_courses = self.lms_system.enrollment_manager.get_student_courses(student.user_id)
                
                # Get assignments for all enrolled courses
                all_assignments = []
                for course in enrolled_courses:
                    course_assignments = self.lms_system.assignment_manager.get_assignments_by_course(course.course_id)
                    all_assignments.extend(course_assignments)
                
                # Update assignments list
                self.assignments_list.clear()
                for assignment in all_assignments:
                    course = self.lms_system.course_manager.get_course(assignment.course_id)
                    course_name = course.name if course else "Unknown Course"
                    item_text = f"{assignment.title} - {course_name} (Due: {assignment.due_date})"
                    self.assignments_list.addItem(item_text)
                
                print(f"[GUI] Student {self.user_email} refreshed assignments: {len(all_assignments)} assignments found")
                
            except Exception as e:
                print(f"[GUI] Error refreshing student assignments: {type(e).__name__}: {e}")
                QMessageBox.critical(self, "Error", f"Failed to refresh assignments:\n{e}")

        def submit_assignment(self):
            """Submit assignment"""
            try:
                if not self.lms_system or not self.lms_system.assignment_manager:
                    QMessageBox.warning(self, "Warning", "Assignment manager not available")
                    return
                
                student = self.lms_system.user_manager.get_user_by_email(self.user_email)
                if not student:
                    QMessageBox.warning(self, "Warning", "Student not found")
                    return
                
                # Get selected assignment
                current_row = self.assignments_list.currentRow()
                if current_row < 0:
                    QMessageBox.warning(self, "Warning", "Please select an assignment to submit")
                    return
                
                # Get assignment text from the list item
                assignment_text = self.assignments_list.currentItem().text()
                
                # Extract assignment title (before the first " - ")
                assignment_title = assignment_text.split(" - ")[0]
                
                # Find the assignment by title and student courses
                enrolled_courses = self.lms_system.enrollment_manager.get_student_courses(student.user_id)
                target_assignment = None
                
                for course in enrolled_courses:
                    course_assignments = self.lms_system.assignment_manager.get_assignments_by_course(course.course_id)
                    for assignment in course_assignments:
                        if assignment.title == assignment_title:
                            target_assignment = assignment
                            break
                    if target_assignment:
                        break
                
                if not target_assignment:
                    QMessageBox.warning(self, "Warning", "Assignment not found")
                    return
                
                # Check if already submitted
                student_submissions = self.lms_system.assignment_manager.get_student_submissions(student.user_id)
                existing_submission = None
                for submission in student_submissions:
                    if submission.assignment_id == target_assignment.assignment_id:
                        existing_submission = submission
                        break
                if existing_submission:
                    QMessageBox.information(self, "Information", "You have already submitted this assignment")
                    return
                
                # Get submission content
                submission_text, ok = QInputDialog.getMultiLineText(self, "Submit Assignment", 
                                                                   f"Submit assignment: {target_assignment.title}\n\nEnter your submission:")
                
                if ok and submission_text.strip():
                    # Create submission
                    submission = self.lms_system.assignment_manager.submit_assignment(
                        student.user_id,
                        target_assignment.assignment_id,
                        {"text": submission_text.strip()}
                    )
                    
                    if submission:
                        QMessageBox.information(self, "Success", "Assignment submitted successfully!")
                        print(f"[GUI] Student {self.user_email} submitted assignment {target_assignment.assignment_id}")
                    else:
                        QMessageBox.warning(self, "Warning", "Failed to submit assignment")
                elif ok:
                    QMessageBox.warning(self, "Warning", "Submission content cannot be empty")
                
            except Exception as e:
                print(f"[GUI] Error submitting assignment: {type(e).__name__}: {e}")
                QMessageBox.critical(self, "Error", f"Failed to submit assignment:\n{e}")

        def refresh_grades(self):
            """Refresh student grades"""
            try:
                if not self.lms_system:
                    QMessageBox.warning(self, "Warning", "LMS system not available")
                    return
                
                student = self.lms_system.user_manager.get_user_by_email(self.user_email)
                if not student:
                    QMessageBox.warning(self, "Warning", "Student not found")
                    return
                
                # Get student's submissions (which contain grades)
                student_submissions = self.lms_system.assignment_manager.get_student_submissions(student.user_id)
                
                # Update grades table - only show graded submissions
                graded_submissions = [sub for sub in student_submissions if sub.grade is not None]
                self.grades_table.setRowCount(len(graded_submissions))
                total_score = 0
                total_possible = 0
                
                for row, submission in enumerate(graded_submissions):
                    # Get assignment and course info
                    assignment = self.lms_system.assignment_manager.get_assignment(submission.assignment_id)
                    course = self.lms_system.course_manager.get_course(assignment.course_id) if assignment else None
                    
                    course_name = course.name if course else "Unknown Course"
                    assignment_title = assignment.title if assignment else "Unknown Assignment"
                    max_score = assignment.max_score if assignment else 0
                    
                    self.grades_table.setItem(row, 0, QTableWidgetItem(course_name))
                    self.grades_table.setItem(row, 1, QTableWidgetItem(assignment_title))
                    self.grades_table.setItem(row, 2, QTableWidgetItem(str(submission.grade)))
                    self.grades_table.setItem(row, 3, QTableWidgetItem(str(max_score)))
                    
                    percentage = (submission.grade / max_score * 100) if max_score > 0 else 0
                    self.grades_table.setItem(row, 4, QTableWidgetItem(f"{percentage:.1f}%"))
                    
                    total_score += submission.grade
                    total_possible += max_score
                
                # Update statistics
                if total_possible > 0:
                    overall_percentage = (total_score / total_possible * 100)
                    self.average_label.setText(f"Average: {overall_percentage:.1f}%")
                    
                    # Simple GPA calculation (4.0 scale)
                    gpa = (overall_percentage / 100) * 4.0
                    self.gpa_label.setText(f"GPA: {gpa:.2f}")
                else:
                    self.average_label.setText("Average: 0.0%")
                    self.gpa_label.setText("GPA: 0.0")
                
                print(f"[GUI] Student {self.user_email} refreshed grades: {len(graded_submissions)} grades found")
                
            except Exception as e:
                print(f"[GUI] Error refreshing student grades: {type(e).__name__}: {e}")
                QMessageBox.critical(self, "Error", f"Failed to refresh grades:\n{e}")
        
        def show_assignment_details(self, item):
            """Show assignment details when an assignment is selected"""
            try:
                assignment_name = item.text().split(" - ")[0]  # Extract title before " - "
                student = self.lms_system.user_manager.get_user_by_email(self.user_email)
                if not student:
                    return
                
                enrolled_courses = self.lms_system.enrollment_manager.get_student_courses(student.user_id)
                
                for course in enrolled_courses:
                    course_assignments = self.lms_system.assignment_manager.get_assignments_by_course(course.course_id)
                    for assignment in course_assignments:
                        if assignment.title == assignment_name:
                            details = f"Title: {assignment.title}\n"
                            details += f"Description: {assignment.description}\n"
                            details += f"Due Date: {assignment.due_date}\n"
                            details += f"Course: {course.name}\n"
                            
                            # Check if already submitted
                            student_submissions = self.lms_system.assignment_manager.get_student_submissions(student.user_id)
                            existing_submission = None
                            for submission in student_submissions:
                                if submission.assignment_id == assignment.assignment_id:
                                    existing_submission = submission
                                    break
                            if existing_submission:
                                details += f"Status: Submitted\n"
                                details += f"Grade: {existing_submission.grade if existing_submission.grade else 'Not graded yet'}"
                            else:
                                details += "Status: Not submitted\n"
                                details += "Grade: Not graded yet"
                            
                            self.assignment_details.setText(details)
                            return
                
                self.assignment_details.setText("Assignment details not found")
                
            except Exception as e:
                QMessageBox.critical(self, "Error", f"Failed to show assignment details: {str(e)}")
        
        def on_tab_changed(self, index):
            """Handle tab changes - refresh data when switching to specific tabs"""
            tab_name = self.tab_widget.tabText(index)
            if tab_name == "Courses":
                self.refresh_courses()
            elif tab_name == "Assignments":
                self.refresh_assignments()
            elif tab_name == "Grades":
                self.refresh_grades()

    class AdminMainWindow(QMainWindow):
        """Admin main window class"""

        def __init__(self, user_email: str, user=None, lms_system=None):
            super().__init__()
            self.user_email = user_email
            self.user = user
            self.lms_system = lms_system
            self.init_ui()

        def init_ui(self):
            """Initialize user interface"""
            self.setWindowTitle(f"GT-LMS Learning Management System (Admin) - {self.user_email}")
            self.setGeometry(200, 200, 800, 600)

            # Create menu bar
            self.create_menu_bar()

            # Create central widget
            central_widget = QWidget()
            self.setCentralWidget(central_widget)

            # Create main layout
            main_layout = QVBoxLayout()
            central_widget.setLayout(main_layout)

            # Create tabs
            self.tab_widget = QTabWidget()
            main_layout.addWidget(self.tab_widget)

            # Add all tabs
            self.create_dashboard_tab()
            self.create_user_management_tab()
            self.create_course_management_tab()
            self.create_system_stats_tab()
            self.create_reports_tab()
            self.create_system_settings_tab()

            # Create status bar
            self.statusBar().showMessage(f"Welcome, {self.user_email}")

        def create_menu_bar(self):
            """Create menu bar"""
            menubar = self.menuBar()
            
            # File menu
            file_menu = menubar.addMenu('File')
            
            # Logout action
            logout_action = QAction('Logout', self)
            logout_action.setShortcut('Ctrl+L')
            logout_action.triggered.connect(self.logout)
            file_menu.addAction(logout_action)
            
            # Exit action
            exit_action = QAction('Exit', self)
            exit_action.setShortcut('Ctrl+Q')
            exit_action.triggered.connect(self.close)
            file_menu.addAction(exit_action)
            
            # Help menu
            help_menu = menubar.addMenu('Help')
            about_action = QAction('About', self)
            about_action.triggered.connect(self.show_about)
            help_menu.addAction(about_action)

        def logout(self):
            """Logout function"""
            print(f"[GUI] User {self.user_email} requested logout")
            try:
                # Execute logout
                if self.lms_system and self.lms_system.auth_system:
                    self.lms_system.auth_system.logout()
                    print(f"[GUI] User {self.user_email} logged out successfully")
                
                # Close current window
                self.close()
                
                # Re-show login window
                if hasattr(self, 'parent_gui') and self.parent_gui:
                    self.parent_gui.show_login_window()
                else:
                    # If no parent_gui, create new login window
                    from PyQt6.QtWidgets import QApplication
                    app = QApplication.instance()
                    if app:
                        login_window = LoginWindow()
                        login_window.show()
                
            except Exception as e:
                print(f"[GUI] Error during logout: {type(e).__name__}: {e}")
                QMessageBox.critical(self, "Logout Error", f"An error occurred during logout:\n{e}")

        def show_about(self):
            """Show about dialog"""
            QMessageBox.about(self, "About", "GT-LMS Learning Management System\nVersion 1.0\n\nA comprehensive learning management system.")

        def create_dashboard_tab(self):
            """Create dashboard tab"""
            dashboard_widget = QWidget()
            layout = QVBoxLayout()

            # Welcome message
            welcome_label = QLabel(f"Welcome to GT-LMS Learning Management System, {self.user_email}!")
            welcome_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
            welcome_font = QFont()
            welcome_font.setPointSize(14)
            welcome_font.setBold(True)
            welcome_label.setFont(welcome_font)
            layout.addWidget(welcome_label)

            # System information
            info_text = QTextEdit()
            info_text.setReadOnly(True)
            info_text.setText("""
    Admin Features Overview:

    • User Management - Manage system user accounts
    • Course Management - Manage all courses
    • System Statistics - View system statistics
    • Report Generation - Generate various reports
    • System Settings - Configure system parameters

    Please use the tabs above to navigate to different functional modules.
            """)
            layout.addWidget(info_text)

            dashboard_widget.setLayout(layout)
            self.tab_widget.addTab(dashboard_widget, "Dashboard")

        def create_user_management_tab(self):
            """Create user management tab"""
            user_widget = QWidget()
            layout = QVBoxLayout()

            # User table
            self.users_table = QTableWidget()
            self.users_table.setColumnCount(5)
            self.users_table.setHorizontalHeaderLabels(["User ID", "Name", "Email", "Type", "Status"])
            self.users_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
            layout.addWidget(self.users_table)

            # Button layout
            button_layout = QHBoxLayout()
            refresh_button = QPushButton("Refresh")
            add_user_button = QPushButton("Add User")
            edit_user_button = QPushButton("Edit User")
            delete_user_button = QPushButton("Delete User")

            # Connect button signals
            refresh_button.clicked.connect(self.refresh_users)
            add_user_button.clicked.connect(self.add_user)
            edit_user_button.clicked.connect(self.edit_user)
            delete_user_button.clicked.connect(self.delete_user)

            button_layout.addWidget(refresh_button)
            button_layout.addWidget(add_user_button)
            button_layout.addWidget(edit_user_button)
            button_layout.addWidget(delete_user_button)

            layout.addLayout(button_layout)
            user_widget.setLayout(layout)
            self.tab_widget.addTab(user_widget, "User Management")

        def create_course_management_tab(self):
            """Create course management tab"""
            course_widget = QWidget()
            layout = QVBoxLayout()

            # Course table
            self.admin_courses_table = QTableWidget()
            self.admin_courses_table.setColumnCount(5)
            self.admin_courses_table.setHorizontalHeaderLabels(["Course ID", "Course Name", "Teacher", "Credits", "Status"])
            self.admin_courses_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
            layout.addWidget(self.admin_courses_table)

            # Button layout
            button_layout = QHBoxLayout()
            refresh_button = QPushButton("Refresh")
            add_course_button = QPushButton("Add Course")
            edit_course_button = QPushButton("Edit Course")
            delete_course_button = QPushButton("Delete Course")

            # Connect button signals
            refresh_button.clicked.connect(self.refresh_courses)
            add_course_button.clicked.connect(self.add_course)
            edit_course_button.clicked.connect(self.edit_course)
            delete_course_button.clicked.connect(self.delete_course)

            button_layout.addWidget(refresh_button)
            button_layout.addWidget(add_course_button)
            button_layout.addWidget(edit_course_button)
            button_layout.addWidget(delete_course_button)

            layout.addLayout(button_layout)
            course_widget.setLayout(layout)
            self.tab_widget.addTab(course_widget, "Course Management")

        def create_system_stats_tab(self):
            """Create system statistics tab"""
            stats_widget = QWidget()
            layout = QVBoxLayout()

            # Statistics information
            stats_group = QGroupBox("System Statistics")
            stats_layout = QFormLayout()

            self.total_users_label = QLabel("0")
            self.total_courses_label = QLabel("0")
            self.total_enrollments_label = QLabel("0")
            self.total_assignments_label = QLabel("0")

            stats_layout.addRow("Total Users:", self.total_users_label)
            stats_layout.addRow("Total Courses:", self.total_courses_label)
            stats_layout.addRow("Total Enrollments:", self.total_enrollments_label)
            stats_layout.addRow("Total Assignments:", self.total_assignments_label)

            stats_group.setLayout(stats_layout)
            layout.addWidget(stats_group)

            # Refresh button
            refresh_button = QPushButton("Refresh Statistics")
            refresh_button.clicked.connect(self.refresh_stats)
            layout.addWidget(refresh_button)

            stats_widget.setLayout(layout)
            self.tab_widget.addTab(stats_widget, "System Statistics")

        def create_reports_tab(self):
            """Create reports tab"""
            reports_widget = QWidget()
            layout = QVBoxLayout()

            # Report type selection
            report_type_group = QGroupBox("Report Type")
            report_type_layout = QHBoxLayout()

            self.report_combo = QComboBox()
            self.report_combo.addItems(["User Report", "Course Report", "Grade Report", "System Activity Report"])
            
            generate_button = QPushButton("Generate Report")
            generate_button.clicked.connect(self.generate_report)
            
            report_type_layout.addWidget(QLabel("Select Report Type:"))
            report_type_layout.addWidget(self.report_combo)
            report_type_layout.addWidget(generate_button)
            
            report_type_group.setLayout(report_type_layout)
            layout.addWidget(report_type_group)

            # Report display area
            self.report_text = QTextEdit()
            self.report_text.setReadOnly(True)
            layout.addWidget(self.report_text)

            reports_widget.setLayout(layout)
            self.tab_widget.addTab(reports_widget, "Report Generation")

        def create_system_settings_tab(self):
            """Create system settings tab"""
            settings_widget = QWidget()
            layout = QVBoxLayout()

            # System settings form
            settings_form = QGroupBox("System Settings")
            form_layout = QFormLayout()

            # Add various setting items
            self.system_name_input = QLineEdit("GT-LMS Learning Management System")
            self.max_students_input = QLineEdit("50")
            self.backup_interval_input = QLineEdit("24")
            
            form_layout.addRow("System Name:", self.system_name_input)
            form_layout.addRow("Max Students per Course:", self.max_students_input)
            form_layout.addRow("Backup Interval (Hours):", self.backup_interval_input)

            settings_form.setLayout(form_layout)
            layout.addWidget(settings_form)

            # Button layout
            button_layout = QHBoxLayout()
            save_settings_button = QPushButton("Save Settings")
            reset_settings_button = QPushButton("Reset Settings")
            backup_button = QPushButton("System Backup")
            restore_button = QPushButton("System Restore")

            # Connect button signals
            save_settings_button.clicked.connect(self.save_settings)
            reset_settings_button.clicked.connect(self.reset_settings)
            backup_button.clicked.connect(self.backup_system)
            restore_button.clicked.connect(self.restore_system)

            button_layout.addWidget(save_settings_button)
            button_layout.addWidget(reset_settings_button)
            button_layout.addWidget(backup_button)
            button_layout.addWidget(restore_button)

            layout.addLayout(button_layout)
            settings_widget.setLayout(layout)
            self.tab_widget.addTab(settings_widget, "System Settings")

        # User management related methods
        def refresh_users(self):
            """Refresh user list"""
            print("[AdminMainWindow] Starting to refresh user list...")
            
            if not self.lms_system or not self.lms_system.user_manager:
                error_msg = "System not initialized or user manager unavailable"
                print(f"[AdminMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            try:
                # Get all users
                print("[AdminMainWindow] Getting all users...")
                users = self.lms_system.user_manager.get_all_users()
                print(f"[AdminMainWindow] Successfully retrieved {len(users)} users")
                
                # Update table
                self.users_table.setRowCount(len(users))
                for row, user in enumerate(users):
                    self.users_table.setItem(row, 0, QTableWidgetItem(user.user_id))
                    self.users_table.setItem(row, 1, QTableWidgetItem(user.name))
                    self.users_table.setItem(row, 2, QTableWidgetItem(user.email))
                    self.users_table.setItem(row, 3, QTableWidgetItem(user.role.value))
                    self.users_table.setItem(row, 4, QTableWidgetItem("Active" if user.is_active else "Inactive"))
                    
                self.statusBar().showMessage(f"Loaded {len(users)} users")
                print("[AdminMainWindow] User list refreshed successfully")
                
            except Exception as e:
                error_msg = f"Failed to refresh user list: {str(e)}"
                print(f"[AdminMainWindow] Error: {error_msg}")
                print(f"[AdminMainWindow] Exception type: {type(e).__name__}")
                import traceback
                traceback.print_exc()
                QMessageBox.critical(self, "Error", error_msg)

        def add_user(self):
            """Add new user"""
            if not self.lms_system or not self.lms_system.user_manager:
                QMessageBox.warning(self, "Error", "System not initialized or user manager unavailable")
                return
                
            # Create add user dialog
            dialog = QDialog(self)
            dialog.setWindowTitle("Add User")
            dialog.setMinimumWidth(400)
            
            layout = QFormLayout()
            
            # User type selection
            user_type_combo = QComboBox()
            user_type_combo.addItems(["Student", "Teacher", "Admin"])
            layout.addRow("User Type:", user_type_combo)
            
            # Input fields
            user_id_input = QLineEdit()
            name_input = QLineEdit()
            email_input = QLineEdit()
            password_input = QLineEdit()
            password_input.setEchoMode(QLineEdit.EchoMode.Password)
            
            layout.addRow("User ID:", user_id_input)
            layout.addRow("Name:", name_input)
            layout.addRow("Email:", email_input)
            layout.addRow("Password:", password_input)
            
            # Buttons
            buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
            buttons.accepted.connect(dialog.accept)
            buttons.rejected.connect(dialog.reject)
            layout.addRow(buttons)
            
            dialog.setLayout(layout)
            
            # Show dialog and process result
            if dialog.exec() == QDialog.DialogCode.Accepted:
                try:
                    # Get user type
                    user_type_map = {"Student": "student", "Teacher": "teacher", "Admin": "admin"}
                    user_type = user_type_map[user_type_combo.currentText()]
                    
                    # Create user data
                    user_data = {
                        "user_id": user_id_input.text(),
                        "name": name_input.text(),
                        "email": email_input.text(),
                        "password": password_input.text()
                    }
                    
                    # Create user
                    new_user = self.lms_system.user_manager.create_user(user_type, user_data)
                    
                    if new_user:
                        QMessageBox.information(self, "Success", f"User {new_user.name} created successfully")
                        self.refresh_users()  # Refresh user list
                    else:
                        QMessageBox.warning(self, "Failed", "Failed to create user")
                except Exception as e:
                    QMessageBox.critical(self, "Error", f"Failed to add user: {str(e)}")

        def edit_user(self):
            """Edit user information"""
            if not self.lms_system or not self.lms_system.user_manager:
                QMessageBox.warning(self, "Error", "System not initialized or user manager unavailable")
                return
                
            # Get selected row
            selected_row = self.users_table.currentRow()
            if selected_row < 0:
                QMessageBox.warning(self, "Notice", "Please select a user to edit first")
                return
                
            # Get user ID
            user_id = self.users_table.item(selected_row, 0).text()
            
            # Get user information
            user = self.lms_system.user_manager.get_user(user_id)
            if not user:
                QMessageBox.warning(self, "Error", "User not found")
                return
                
            # Create edit user dialog
            dialog = QDialog(self)
            dialog.setWindowTitle(f"Edit User - {user.name}")
            dialog.setMinimumWidth(400)
            
            layout = QFormLayout()
            
            # Input fields
            name_input = QLineEdit(user.name)
            email_input = QLineEdit(user.email)
            
            layout.addRow("Name:", name_input)
            layout.addRow("Email:", email_input)
            
            # User status
            status_checkbox = QCheckBox("Active")
            status_checkbox.setChecked(user.is_active)
            layout.addRow("User Status:", status_checkbox)
            
            # Buttons
            buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
            buttons.accepted.connect(dialog.accept)
            buttons.rejected.connect(dialog.reject)
            layout.addRow(buttons)
            
            dialog.setLayout(layout)
            
            # Show dialog and process result
            if dialog.exec() == QDialog.DialogCode.Accepted:
                try:
                    # Update user data
                    update_data = {
                        "name": name_input.text(),
                        "email": email_input.text(),
                        "is_active": status_checkbox.isChecked()
                    }
                    
                    # Update user
                    success = self.lms_system.user_manager.update_user(user_id, update_data)
                    
                    if success:
                        QMessageBox.information(self, "Success", f"User {user.name} updated successfully")
                        self.refresh_users()  # Refresh user list
                    else:
                        QMessageBox.warning(self, "Failed", "Failed to update user")
                except Exception as e:
                    QMessageBox.critical(self, "Error", f"Failed to update user: {str(e)}")

        def delete_user(self):
            """Delete user"""
            if not self.lms_system or not self.lms_system.user_manager:
                QMessageBox.warning(self, "Error", "System not initialized or user manager unavailable")
                return
                
            # Get selected row
            selected_row = self.users_table.currentRow()
            if selected_row < 0:
                QMessageBox.warning(self, "Notice", "Please select a user to delete first")
                return
                
            # Get user information
            user_id = self.users_table.item(selected_row, 0).text()
            user_name = self.users_table.item(selected_row, 1).text()
            
            # Confirm deletion
            reply = QMessageBox.question(
                self, "Confirm Delete", 
                f"Are you sure you want to delete user {user_name} (ID: {user_id})?\nThis operation cannot be undone!",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                QMessageBox.StandardButton.No
            )
            
            if reply == QMessageBox.StandardButton.Yes:
                try:
                    # Delete user
                    success = self.lms_system.user_manager.delete_user(user_id)
                    
                    if success:
                        QMessageBox.information(self, "Success", f"User {user_name} deleted successfully")
                        self.refresh_users()  # Refresh user list
                    else:
                        QMessageBox.warning(self, "Failed", "Failed to delete user")
                except Exception as e:
                    QMessageBox.critical(self, "Error", f"Failed to delete user: {str(e)}")

        # Course management related methods
        def refresh_courses(self):
            """Refresh course list"""
            print("[AdminMainWindow] Starting to refresh course list...")
            
            if not self.lms_system or not self.lms_system.course_manager:
                error_msg = "System not initialized or course manager unavailable"
                print(f"[AdminMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            try:
                # Get all courses
                print("[AdminMainWindow] Getting all courses...")
                courses = self.lms_system.course_manager.get_all_courses()
                print(f"[AdminMainWindow] Successfully retrieved {len(courses)} courses")
                
                # Update table
                self.admin_courses_table.setRowCount(len(courses))
                for row, course in enumerate(courses):
                    self.admin_courses_table.setItem(row, 0, QTableWidgetItem(course.course_id))
                    self.admin_courses_table.setItem(row, 1, QTableWidgetItem(course.name))
                    self.admin_courses_table.setItem(row, 2, QTableWidgetItem(course.instructor_name if hasattr(course, 'instructor_name') else "Not specified"))
                    self.admin_courses_table.setItem(row, 3, QTableWidgetItem(str(course.credits) if hasattr(course, 'credits') else "0"))
                    self.admin_courses_table.setItem(row, 4, QTableWidgetItem("Active" if hasattr(course, 'is_active') and course.is_active else "Inactive"))
                    
                self.statusBar().showMessage(f"Loaded {len(courses)} courses")
                print("[AdminMainWindow] Course list refreshed successfully")
                
            except Exception as e:
                error_msg = f"Failed to refresh course list: {str(e)}"
                print(f"[AdminMainWindow] Error: {error_msg}")
                print(f"[AdminMainWindow] Exception type: {type(e).__name__}")
                import traceback
                traceback.print_exc()
                QMessageBox.critical(self, "Error", error_msg)

        def add_course(self):
            """Add new course"""
            print("[AdminMainWindow] Starting to add new course...")
            
            if not self.lms_system or not self.lms_system.course_manager:
                error_msg = "System not initialized or course manager unavailable"
                print(f"[AdminMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Create add course dialog
            dialog = QDialog(self)
            dialog.setWindowTitle("Add Course")
            dialog.setMinimumWidth(400)
            
            layout = QFormLayout()
            
            # Input fields
            course_id_input = QLineEdit()
            name_input = QLineEdit()
            description_input = QTextEdit()
            credits_input = QLineEdit("3")
            
            # Get teacher list for dropdown
            teachers = self.lms_system.user_manager.get_users_by_role(UserRole.TEACHER)
            teacher_combo = QComboBox()
            if teachers:
                for teacher in teachers:
                    teacher_combo.addItem(f"{teacher.name} ({teacher.email})", teacher.user_id)
            else:
                teacher_combo.addItem("No teachers available", "")
            
            layout.addRow("Course ID:", course_id_input)
            layout.addRow("Course Name:", name_input)
            layout.addRow("Course Description:", description_input)
            layout.addRow("Teacher:", teacher_combo)
            layout.addRow("Credits:", credits_input)
            
            # Buttons
            buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
            buttons.accepted.connect(dialog.accept)
            buttons.rejected.connect(dialog.reject)
            layout.addRow(buttons)
            
            dialog.setLayout(layout)
            
            # Show dialog and process result
            if dialog.exec() == QDialog.DialogCode.Accepted:
                try:
                    # Create course data
                    teacher_id = teacher_combo.currentData()
                    if not teacher_id:
                        QMessageBox.warning(self, "Error", "Please select a teacher")
                        return
                    
                    course_data = {
                        "course_id": course_id_input.text(),
                        "name": name_input.text(),
                        "description": description_input.toPlainText(),
                        "teacher_id": teacher_id,
                        "credits": int(credits_input.text())
                    }
                    
                    print(f"[AdminMainWindow] Creating course: {course_data}")
                    
                    # Create course
                    new_course = self.lms_system.course_manager.create_course(course_data)
                    
                    if new_course:
                        success_msg = f"Course {new_course.name} created successfully"
                        print(f"[AdminMainWindow] Success: {success_msg}")
                        QMessageBox.information(self, "Success", success_msg)
                        self.refresh_courses()  # Refresh course list
                    else:
                        error_msg = "Failed to create course"
                        print(f"[AdminMainWindow] Failed: {error_msg}")
                        QMessageBox.warning(self, "Failed", error_msg)
                        
                except Exception as e:
                    error_msg = f"Failed to add course: {str(e)}"
                    print(f"[AdminMainWindow] Error: {error_msg}")
                    print(f"[AdminMainWindow] Exception type: {type(e).__name__}")
                    import traceback
                    traceback.print_exc()
                    QMessageBox.critical(self, "Error", error_msg)

        def edit_course(self):
            """Edit course information"""
            print("[AdminMainWindow] Starting to edit course")
            
            if not self.lms_system or not self.lms_system.course_manager:
                error_msg = "System not initialized or course manager unavailable"
                print(f"[AdminMainWindow] Failed to edit course: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Get selected row
            selected_row = self.admin_courses_table.currentRow()
            if selected_row < 0:
                print("[AdminMainWindow] Failed to edit course: no course selected")
                QMessageBox.warning(self, "Notice", "Please select a course to edit first")
                return
                
            # Get course ID
            course_id = self.admin_courses_table.item(selected_row, 0).text()
            print(f"[AdminMainWindow] Editing course ID: {course_id}")
            
            # Get course information
            course = self.lms_system.course_manager.get_course(course_id)
            if not course:
                error_msg = f"Course not found: {course_id}"
                print(f"[AdminMainWindow] {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            print(f"[AdminMainWindow] Found course: {course.name}")
            
            # Create edit course dialog
            dialog = QDialog(self)
            dialog.setWindowTitle(f"Edit Course - {course.name}")
            dialog.setMinimumWidth(400)
            
            layout = QFormLayout()
            
            # Input fields
            name_input = QLineEdit(course.name)
            description_input = QTextEdit()
            description_input.setPlainText(course.description if hasattr(course, 'description') else "")
            teacher_input = QLineEdit(course.instructor_name if hasattr(course, 'instructor_name') else "")
            credits_input = QLineEdit(str(course.credits) if hasattr(course, 'credits') else "3")
            
            layout.addRow("Course Name:", name_input)
            layout.addRow("Course Description:", description_input)
            layout.addRow("Teacher:", teacher_input)
            layout.addRow("Credits:", credits_input)
            

            
            # Course status
            status_checkbox = QCheckBox("Active")
            status_checkbox.setChecked(hasattr(course, 'is_active') and course.is_active)
            layout.addRow("Course Status:", status_checkbox)
            
            # Buttons
            buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
            buttons.accepted.connect(dialog.accept)
            buttons.rejected.connect(dialog.reject)
            layout.addRow(buttons)
            
            dialog.setLayout(layout)
            
            # Show dialog and process result
            if dialog.exec() == QDialog.DialogCode.Accepted:
                try:
                    # Update course data
                    update_data = {
                        "name": name_input.text(),
                        "description": description_input.toPlainText(),
                        "instructor_name": teacher_input.text(),
                        "credits": int(credits_input.text())
                    }
                    
                    # Only update status if course object has is_active attribute
                    if hasattr(course, 'is_active'):
                        update_data["is_active"] = status_checkbox.isChecked()
                    
                    print(f"[AdminMainWindow] Updating course data: {update_data}")
                    
                    # Update course
                    success = self.lms_system.course_manager.update_course(course_id, update_data)
                    
                    if success:
                        print(f"[AdminMainWindow] Course {course.name} updated successfully")
                        QMessageBox.information(self, "Success", f"Course {course.name} updated successfully")
                        self.refresh_courses()  # Refresh course list
                    else:
                        print("[AdminMainWindow] Failed to update course")
                        QMessageBox.warning(self, "Failed", "Failed to update course")
                except Exception as e:
                    error_msg = f"Failed to update course: {str(e)}"
                    print(f"[AdminMainWindow] {error_msg}")
                    print(f"[AdminMainWindow] Exception type: {type(e).__name__}")
                    import traceback
                    traceback.print_exc()
                    QMessageBox.critical(self, "Error", error_msg)

        def delete_course(self):
            """Delete course"""
            print("[AdminMainWindow] Starting to delete course")
            
            if not self.lms_system or not self.lms_system.course_manager:
                error_msg = "System not initialized or course manager unavailable"
                print(f"[AdminMainWindow] Failed to delete course: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Get selected row
            selected_row = self.admin_courses_table.currentRow()
            if selected_row < 0:
                print("[AdminMainWindow] Failed to delete course: no course selected")
                QMessageBox.warning(self, "Notice", "Please select a course to delete first")
                return
                
            # Get course information
            course_id = self.admin_courses_table.item(selected_row, 0).text()
            course_name = self.admin_courses_table.item(selected_row, 1).text()
            
            print(f"[AdminMainWindow] Preparing to delete course: {course_name} (ID: {course_id})")
            
            # Confirm deletion
            reply = QMessageBox.question(
                self, "Confirm Delete", 
                f"Are you sure you want to delete course {course_name} (ID: {course_id})?\nThis action cannot be undone!",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                QMessageBox.StandardButton.No
            )
            
            if reply == QMessageBox.StandardButton.Yes:
                print(f"[AdminMainWindow] User confirmed deletion of course: {course_name}")
                try:
                    # Delete course
                    success = self.lms_system.course_manager.delete_course(course_id)
                    
                    if success:
                        print(f"[AdminMainWindow] Course {course_name} deleted successfully")
                        QMessageBox.information(self, "Success", f"Course {course_name} deleted successfully")
                        self.refresh_courses()  # Refresh course list
                    else:
                        print(f"[AdminMainWindow] Failed to delete course {course_name}")
                        QMessageBox.warning(self, "Failed", "Failed to delete course")
                except Exception as e:
                    error_msg = f"Failed to delete course: {str(e)}"
                    print(f"[AdminMainWindow] {error_msg}")
                    print(f"[AdminMainWindow] Exception type: {type(e).__name__}")
                    import traceback
                    traceback.print_exc()
                    QMessageBox.critical(self, "Error", error_msg)
            else:
                print(f"[AdminMainWindow] User cancelled deletion of course: {course_name}")

        # System statistics related methods
        def refresh_stats(self):
            """Refresh system statistics"""
            print("[AdminMainWindow] Starting to refresh system statistics")
            
            if not self.lms_system:
                error_msg = "System not initialized"
                print(f"[AdminMainWindow] Failed to refresh statistics: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            try:
                # Get user statistics
                if self.lms_system.user_manager:
                    print("[AdminMainWindow] Getting user statistics")
                    user_stats = self.lms_system.user_manager.get_user_count()
                    user_count = user_stats.get('total', 0)
                    self.total_users_label.setText(str(user_count))
                    print(f"[AdminMainWindow] User statistics: {user_count}")
                else:
                    self.total_users_label.setText("0")
                    print("[AdminMainWindow] User manager unavailable")
                
                # Get course statistics
                if self.lms_system.course_manager:
                    print("[AdminMainWindow] Getting course statistics")
                    courses = self.lms_system.course_manager.get_all_courses()
                    course_count = len(courses)
                    self.total_courses_label.setText(str(course_count))
                    print(f"[AdminMainWindow] Course statistics: {course_count}")
                else:
                    self.total_courses_label.setText("0")
                    print("[AdminMainWindow] Course manager unavailable")
                
                # Get enrollment statistics
                if self.lms_system.enrollment_manager:
                    print("[AdminMainWindow] Getting enrollment statistics")
                    enrollments = self.lms_system.enrollment_manager.enrollments
                    enrollment_count = len(enrollments) if enrollments else 0
                    self.total_enrollments_label.setText(str(enrollment_count))
                    print(f"[AdminMainWindow] Enrollment statistics: {enrollment_count}")
                else:
                    self.total_enrollments_label.setText("0")
                    print("[AdminMainWindow] Enrollment manager unavailable")
                
                # Get assignment statistics
                if self.lms_system.assignment_manager:
                    print("[AdminMainWindow] Getting assignment statistics")
                    assignments = self.lms_system.assignment_manager.assignments
                    assignment_count = len(assignments) if assignments else 0
                    self.total_assignments_label.setText(str(assignment_count))
                    print(f"[AdminMainWindow] Assignment statistics: {assignment_count}")
                else:
                    self.total_assignments_label.setText("0")
                    print("[AdminMainWindow] Assignment manager unavailable")
                
                print("[AdminMainWindow] Statistics refreshed successfully")
                self.statusBar().showMessage("Statistics refreshed")
            except Exception as e:
                error_msg = f"Failed to refresh statistics: {str(e)}"
                error_msg = f"Failed to refresh statistics: {str(e)}"
                print(f"[AdminMainWindow] {error_msg}")
                print(f"[AdminMainWindow] Exception type: {type(e).__name__}")
                import traceback
                traceback.print_exc()
                QMessageBox.critical(self, "Error", error_msg)

        # Report generation related methods
        def generate_report(self):
            """Generate report"""
            print("[AdminMainWindow] Starting to generate report")
            
            if not self.lms_system:
                error_msg = "System not initialized"
                print(f"[AdminMainWindow] Failed to generate report: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            report_type = self.report_combo.currentText()
            print(f"[AdminMainWindow] Report type: {report_type}")
            
            try:
                if report_type == "User Report":
                    print("[AdminMainWindow] Generating user report")
                    self.generate_user_report()
                elif report_type == "Course Report":
                    print("[AdminMainWindow] Generating course report")
                    self.generate_course_report()
                elif report_type == "Grade Report":
                    print("[AdminMainWindow] Generating grade report")
                    self.generate_grade_report()
                elif report_type == "System Activity Report":
                    print("[AdminMainWindow] Generating system activity report")
                    self.generate_activity_report()
                else:
                    error_msg = f"Unknown report type: {report_type}"
                    print(f"[AdminMainWindow] {error_msg}")
                    QMessageBox.warning(self, "Error", error_msg)
            except Exception as e:
                error_msg = f"Failed to generate report: {str(e)}"
                print(f"[AdminMainWindow] {error_msg}")
                print(f"[AdminMainWindow] Exception type: {type(e).__name__}")
                import traceback
                traceback.print_exc()
                QMessageBox.critical(self, "Error", error_msg)

        def generate_user_report(self):
            """Generate user report"""
            if not self.lms_system.user_manager:
                self.report_text.setText("User manager unavailable")
                return
                
            users = self.lms_system.user_manager.get_all_users()
            
            # Count user types
            student_count = sum(1 for u in users if u.role.value == "student")
            teacher_count = sum(1 for u in users if u.role.value == "teacher")
            admin_count = sum(1 for u in users if u.role.value == "admin")
            active_count = sum(1 for u in users if u.is_active)
            
            # Generate report text
            report = f"User Report\nGenerated at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
            report += f"Total Users: {len(users)}\n"
            report += f"Active Users: {active_count}\n"
            report += f"Students: {student_count}\n"
            report += f"Teachers: {teacher_count}\n"
            report += f"Admins: {admin_count}\n\n"
            
            report += "User Details:\n"
            report += "-" * 80 + "\n"
            report += f"{'User ID':<15} {'Name':<20} {'Email':<25} {'Type':<10} {'Status':<10}\n"
            report += "-" * 80 + "\n"
            
            for user in users:
                status = "Active" if user.is_active else "Inactive"
                report += f"{user.user_id:<15} {user.name:<20} {user.email:<25} {user.role.value:<10} {status:<10}\n"
            
            self.report_text.setText(report)
            self.statusBar().showMessage("User report generated successfully")

        def generate_course_report(self):
            """Generate course report"""
            if not self.lms_system.course_manager:
                self.report_text.setText("Course manager unavailable")
                return
                
            courses = self.lms_system.course_manager.get_all_courses()
            
            # Generate report text
            report = f"Course Report\nGenerated at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
            report += f"Total Courses: {len(courses)}\n\n"
            
            report += "Course Details:\n"
            report += "-" * 80 + "\n"
            report += f"{'Course ID':<15} {'Course Name':<25} {'Teacher':<20} {'Credits':<7} {'Status':<10}\n"
            report += "-" * 80 + "\n"
            
            for course in courses:
                teacher = course.instructor_name if hasattr(course, 'instructor_name') else "Not specified"
                credits = str(course.credits) if hasattr(course, 'credits') else "0"
                status = "Active" if hasattr(course, 'is_active') and course.is_active else "Inactive"
                
                report += f"{course.course_id:<15} {course.name:<25} {teacher:<20} {credits:<7} {status:<10}\n"
            
            self.report_text.setText(report)
            self.statusBar().showMessage("Course report generated successfully")

        def generate_grade_report(self):
            """Generate grade report"""
            report = f"Grade Report\nGenerated at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
            report += "Grade statistics feature is under development...\n"
            self.report_text.setText(report)
            self.statusBar().showMessage("Grade report generated successfully")

        def generate_activity_report(self):
            """Generate system activity report"""
            report = f"System Activity Report\nGenerated at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
            report += "System activity statistics feature is under development...\n"
            self.report_text.setText(report)
            self.statusBar().showMessage("System activity report generated successfully")

        # System settings related methods
        def save_settings(self):
            """Save system settings"""
            try:
                # Get settings values
                system_name = self.system_name_input.text()
                max_students = self.max_students_input.text()
                backup_interval = self.backup_interval_input.text()
                
                # Validate input
                try:
                    max_students = int(max_students)
                    backup_interval = int(backup_interval)
                except ValueError:
                    QMessageBox.warning(self, "Error", "Max students and backup interval must be numbers")
                    return
                
                # Here settings should be saved to configuration file or database
                # Currently only shows success message
                QMessageBox.information(self, "Success", "System settings saved successfully")
                self.statusBar().showMessage("System settings saved")
            except Exception as e:
                QMessageBox.critical(self, "Error", f"Failed to save system settings: {str(e)}")

        def reset_settings(self):
            """Reset system settings"""
            reply = QMessageBox.question(
                self, "Confirm Reset", 
                "Are you sure you want to reset all system settings?",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                QMessageBox.StandardButton.No
            )
            
            if reply == QMessageBox.StandardButton.Yes:
                try:
                    # Reset to default values
                    self.system_name_input.setText("GT-LMS Learning Management System")
                    self.max_students_input.setText("50")
                    self.backup_interval_input.setText("24")
                    
                    QMessageBox.information(self, "Success", "System settings reset successfully")
                    self.statusBar().showMessage("System settings reset")
                except Exception as e:
                    QMessageBox.critical(self, "Error", f"Failed to reset system settings: {str(e)}")

        def backup_system(self):
            """Backup system data"""
            try:
                if not self.lms_system:
                    QMessageBox.warning(self, "Error", "System not initialized")
                    return
                
                # Execute backup
                success = self.lms_system.save_data()
                
                if success:
                    QMessageBox.information(self, "Success", f"System data backup successful\nBackup time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
                    self.statusBar().showMessage("System data backup completed")
                else:
                    QMessageBox.warning(self, "Failed", "System data backup failed")
            except Exception as e:
                QMessageBox.critical(self, "Error", f"System data backup failed: {str(e)}")

        def restore_system(self):
            """Restore system data"""
            reply = QMessageBox.question(
                self, "Confirm Restore", 
                "Are you sure you want to restore system data?\nThis operation will overwrite current data!",
                QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                QMessageBox.StandardButton.No
            )
            
            if reply == QMessageBox.StandardButton.Yes:
                try:
                    if not self.lms_system:
                        QMessageBox.warning(self, "Error", "System not initialized")
                        return
                    
                    # Execute restore
                    success = self.lms_system.load_data()
                    
                    if success:
                        QMessageBox.information(self, "Success", f"System data restore successful\nRestore time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
                        self.statusBar().showMessage("System data restore completed")
                        
                        # Refresh all data
                        self.refresh_users()
                        self.refresh_courses()
                        self.refresh_stats()
                    else:
                        QMessageBox.warning(self, "Failed", "System data restore failed")
                except Exception as e:
                    QMessageBox.critical(self, "Error", f"System data restore failed: {str(e)}")

    class TeacherMainWindow(QMainWindow):
        """Teacher main window class"""

        def __init__(self, user_email: str, user=None, lms_system=None):
            super().__init__()
            self.user_email = user_email
            self.user = user
            self.lms_system = lms_system
            self.init_ui()

        def init_ui(self):
            """Initialize user interface"""
            self.setWindowTitle(f"GT-LMS Learning Management System (Teacher) - {self.user_email}")
            self.setGeometry(200, 200, 800, 600)

            # Create menu bar
            self.create_menu_bar()

            # Create central widget
            central_widget = QWidget()
            self.setCentralWidget(central_widget)

            # Create main layout
            main_layout = QVBoxLayout()
            central_widget.setLayout(main_layout)

            # Create tabs
            self.tab_widget = QTabWidget()
            main_layout.addWidget(self.tab_widget)

            # Add tabs
            self.create_dashboard_tab()
            self.create_course_management_tab()
            self.create_assignment_management_tab()
            self.create_grading_tab()
            self.create_class_stats_tab()

            # Create status bar
            self.statusBar().showMessage(f"Welcome, {self.user_email}")

        def create_menu_bar(self):
            """Create menu bar"""
            menubar = self.menuBar()
            
            # File menu
            file_menu = menubar.addMenu('File')
            
            # Logout action
            logout_action = QAction('Logout', self)
            logout_action.setShortcut('Ctrl+L')
            logout_action.triggered.connect(self.logout)
            file_menu.addAction(logout_action)
            
            # Exit action
            exit_action = QAction('Exit', self)
            exit_action.setShortcut('Ctrl+Q')
            exit_action.triggered.connect(self.close)
            file_menu.addAction(exit_action)
            
            # Help menu
            help_menu = menubar.addMenu('Help')
            about_action = QAction('About', self)
            about_action.triggered.connect(self.show_about)
            help_menu.addAction(about_action)

        def logout(self):
            """Logout function"""
            print(f"[GUI] Teacher {self.user_email} requested logout")
            try:
                # Execute logout
                if self.lms_system and self.lms_system.auth_system:
                    self.lms_system.auth_system.logout()
                    print(f"[GUI] Teacher {self.user_email} logout successful")
                
                # Close current window
                self.close()
                
                # Show login window again
                if hasattr(self, 'parent_gui') and self.parent_gui:
                    self.parent_gui.show_login_window()
                else:
                    # If no parent_gui, create new login window
                    from PyQt6.QtWidgets import QApplication
                    app = QApplication.instance()
                    if app:
                        login_window = LoginWindow()
                        login_window.show()
                
            except Exception as e:
                print(f"[GUI] Error during teacher logout: {type(e).__name__}: {e}")
                QMessageBox.critical(self, "Logout Error", f"Error occurred during logout:\n{e}")

        def show_about(self):
            """Show about dialog"""
            QMessageBox.about(self, "About", "GT-LMS Learning Management System\nVersion 1.0\n\nA comprehensive learning management system.")

        def create_dashboard_tab(self):
            """Create dashboard tab"""
            dashboard_widget = QWidget()
            layout = QVBoxLayout()

            # Welcome message
            welcome_label = QLabel(f"Welcome to GT-LMS Learning Management System, {self.user_email}!")
            welcome_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
            welcome_font = QFont()
            welcome_font.setPointSize(14)
            welcome_font.setBold(True)
            welcome_label.setFont(welcome_font)
            layout.addWidget(welcome_label)

            # System information
            info_text = QTextEdit()
            info_text.setReadOnly(True)
            info_text.setText("""
    Teacher Features Overview:

    • Course Management - Manage your courses
    • Assignment Management - Create and manage assignments
    • Grade Management - Grade assignments and enter scores
    • Class Statistics - View class statistics

    Please use the tabs above to navigate to different modules.
            """)
            layout.addWidget(info_text)

            dashboard_widget.setLayout(layout)
            self.tab_widget.addTab(dashboard_widget, "Dashboard")

        def create_course_management_tab(self):
            """Create course management tab"""
            course_widget = QWidget()
            layout = QVBoxLayout()

            # Course table
            self.teacher_courses_table = QTableWidget()
            self.teacher_courses_table.setColumnCount(4)
            self.teacher_courses_table.setHorizontalHeaderLabels(["Course ID", "Course Name", "Students", "Status"])
            self.teacher_courses_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
            layout.addWidget(self.teacher_courses_table)

            # Button layout
            button_layout = QHBoxLayout()
            refresh_button = QPushButton("Refresh")
            create_course_button = QPushButton("Create Course")
            edit_course_button = QPushButton("Edit Course")
            view_students_button = QPushButton("View Students")

            # Connect button signals to slots
            refresh_button.clicked.connect(self.refresh_teacher_courses)
            create_course_button.clicked.connect(self.create_teacher_course)
            edit_course_button.clicked.connect(self.edit_teacher_course)
            view_students_button.clicked.connect(self.view_teacher_course_students)

            button_layout.addWidget(refresh_button)
            button_layout.addWidget(create_course_button)
            button_layout.addWidget(edit_course_button)
            button_layout.addWidget(view_students_button)

            layout.addLayout(button_layout)
            course_widget.setLayout(layout)
            self.tab_widget.addTab(course_widget, "Course Management")

        def create_assignment_management_tab(self):
            """Create assignment management tab"""
            assignment_widget = QWidget()
            layout = QVBoxLayout()

            # Assignment table
            self.teacher_assignments_table = QTableWidget()
            self.teacher_assignments_table.setColumnCount(5)
            self.teacher_assignments_table.setHorizontalHeaderLabels(["Assignment ID", "Assignment Name", "Course", "Due Date", "Submissions"])
            self.teacher_assignments_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
            layout.addWidget(self.teacher_assignments_table)

            # Button layout
            button_layout = QHBoxLayout()
            refresh_button = QPushButton("Refresh")
            create_assignment_button = QPushButton("Create Assignment")
            edit_assignment_button = QPushButton("Edit Assignment")
            view_submissions_button = QPushButton("View Submissions")

            button_layout.addWidget(refresh_button)
            button_layout.addWidget(create_assignment_button)
            button_layout.addWidget(edit_assignment_button)
            button_layout.addWidget(view_submissions_button)

            layout.addLayout(button_layout)
            assignment_widget.setLayout(layout)
            self.tab_widget.addTab(assignment_widget, "Assignment Management")
            
            # Connect assignment buttons
            refresh_button.clicked.connect(self.refresh_teacher_assignments)
            create_assignment_button.clicked.connect(self.create_teacher_assignment)
            edit_assignment_button.clicked.connect(self.edit_teacher_assignment)
            view_submissions_button.clicked.connect(self.view_teacher_submissions)

        def create_grading_tab(self):
            """Create grading management tab"""
            grading_widget = QWidget()
            layout = QVBoxLayout()

            # Grades table
            self.grading_table = QTableWidget()
            self.grading_table.setColumnCount(6)
            self.grading_table.setHorizontalHeaderLabels(["Student", "Course", "Assignment", "Submission Status", "Score", "Action"])
            self.grading_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
            layout.addWidget(self.grading_table)

            # Button layout
            button_layout = QHBoxLayout()
            refresh_button = QPushButton("Refresh")
            grade_button = QPushButton("Grade Assignment")
            export_grades_button = QPushButton("Export Grades")

            button_layout.addWidget(refresh_button)
            button_layout.addWidget(grade_button)
            button_layout.addWidget(export_grades_button)

            layout.addLayout(button_layout)
            grading_widget.setLayout(layout)
            self.tab_widget.addTab(grading_widget, "Grading Management")
            
            # Connect grading buttons
            refresh_button.clicked.connect(self.refresh_grading)
            grade_button.clicked.connect(self.grade_assignment)
            export_grades_button.clicked.connect(self.export_grades)

        def create_class_stats_tab(self):
            """Create class statistics tab"""
            stats_widget = QWidget()
            layout = QVBoxLayout()

            # Statistics information
            stats_group = QGroupBox("Class Statistics")
            stats_layout = QFormLayout()

            self.total_courses_label = QLabel("0")
            self.total_students_label = QLabel("0")
            self.avg_grade_label = QLabel("0.0")
            self.submission_rate_label = QLabel("0%")

            stats_layout.addRow("Courses Taught:", self.total_courses_label)
            stats_layout.addRow("Total Students:", self.total_students_label)
            stats_layout.addRow("Average Grade:", self.avg_grade_label)
            stats_layout.addRow("Assignment Submission Rate:", self.submission_rate_label)

            stats_group.setLayout(stats_layout)
            layout.addWidget(stats_group)

            # Data visualization section
            if MATPLOTLIB_AVAILABLE:
                # Create chart container
                chart_group = QGroupBox("Grade Visualization")
                chart_layout = QVBoxLayout()
                
                # Create chart
                self.teacher_chart = GradeChart(stats_widget, width=5, height=4, dpi=100)
                chart_layout.addWidget(self.teacher_chart)
                
                chart_group.setLayout(chart_layout)
                layout.addWidget(chart_group)
                
                # Add sample data
                self.sample_courses = ["Course 1", "Course 2", "Course 3"]
                self.sample_grades = [85, 78, 92]
                
                # Initially display bar chart
                self.teacher_chart.plot_grades(self.sample_courses, self.sample_grades)

            # Refresh button
            refresh_button = QPushButton("Refresh Statistics")
            layout.addWidget(refresh_button)

            stats_widget.setLayout(layout)
            self.tab_widget.addTab(stats_widget, "Class Statistics")
            
        def show_bar_chart(self):
            """Display grade bar chart"""
            if MATPLOTLIB_AVAILABLE and hasattr(self, 'grade_chart'):
                self.grade_chart.plot_grades(self.sample_courses, self.sample_grades)
                
        def show_histogram(self):
            """Display grade distribution histogram"""
            if MATPLOTLIB_AVAILABLE and hasattr(self, 'grade_chart'):
                self.grade_chart.plot_grade_distribution(self.sample_grades)
                
        def refresh_chart(self):
            """Refresh chart data"""
            if MATPLOTLIB_AVAILABLE and hasattr(self, 'grade_chart'):
                # Here you can get actual data from database
                # Now using random data to simulate
                import random
                self.sample_grades = [random.randint(60, 100) for _ in range(len(self.sample_courses))]
                self.show_bar_chart()

        def refresh_teacher_courses(self):
            """Refresh teacher's course list"""
            print(f"[TeacherMainWindow] Starting to refresh teacher's course list for teacher: {self.user_email}")
            
            if not self.lms_system or not self.lms_system.course_manager:
                error_msg = "System not initialized or course manager unavailable"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            try:
                # Get current teacher user
                user_manager = self.lms_system.user_manager
                if not user_manager:
                    error_msg = "User manager unavailable"
                    print(f"[TeacherMainWindow] Error: {error_msg}")
                    QMessageBox.warning(self, "Error", error_msg)
                    return
                    
                current_teacher = user_manager.get_user_by_email(self.user_email)
                if not current_teacher:
                    error_msg = "Current teacher user not found"
                    print(f"[TeacherMainWindow] Error: {error_msg}")
                    QMessageBox.warning(self, "Error", error_msg)
                    return
                
                teacher_id = current_teacher.user_id
                print(f"[TeacherMainWindow] Getting courses for teacher ID: {teacher_id}")
                
                # Get teacher's courses
                courses = self.lms_system.course_manager.get_teacher_courses(teacher_id)
                print(f"[TeacherMainWindow] Successfully retrieved {len(courses)} courses for teacher")
                
                # Update table
                self.teacher_courses_table.setRowCount(len(courses))
                for row, course in enumerate(courses):
                    self.teacher_courses_table.setItem(row, 0, QTableWidgetItem(course.course_id))
                    self.teacher_courses_table.setItem(row, 1, QTableWidgetItem(course.name))
                    
                    # Get student count
                    student_count = len(getattr(course, 'student_ids', []))
                    self.teacher_courses_table.setItem(row, 2, QTableWidgetItem(str(student_count)))
                    
                    status = "Active" if getattr(course, 'is_active', True) else "Inactive"
                    self.teacher_courses_table.setItem(row, 3, QTableWidgetItem(status))
                    
                self.statusBar().showMessage(f"Loaded {len(courses)} courses")
                print("[TeacherMainWindow] Teacher course list refreshed successfully")
                
            except Exception as e:
                error_msg = f"Failed to refresh teacher course list: {str(e)}"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                print(f"[TeacherMainWindow] Exception type: {type(e).__name__}")
                import traceback
                traceback.print_exc()
                QMessageBox.critical(self, "Error", error_msg)

        def create_teacher_course(self):
            """Create a new course"""
            print("[TeacherMainWindow] Starting to create new course...")
            
            if not self.lms_system or not self.lms_system.course_manager:
                error_msg = "System not initialized or course manager unavailable"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Get current teacher user
            user_manager = self.lms_system.user_manager
            if not user_manager:
                error_msg = "User manager unavailable"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            current_teacher = user_manager.get_user_by_email(self.user_email)
            if not current_teacher:
                error_msg = "Current teacher user not found"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            teacher_id = current_teacher.user_id
            
            # Create add course dialog
            dialog = QDialog(self)
            dialog.setWindowTitle("Create Course")
            dialog.setMinimumWidth(400)
            
            layout = QFormLayout()
            
            # Input fields
            course_id_input = QLineEdit()
            name_input = QLineEdit()
            description_input = QTextEdit()
            max_students_input = QLineEdit("30")
            credits_input = QLineEdit("3")
            
            layout.addRow("Course ID (optional):", course_id_input)
            layout.addRow("Course Name:*", name_input)
            layout.addRow("Course Description:*", description_input)
            layout.addRow("Max Students:*", max_students_input)
            layout.addRow("Credits:*", credits_input)
            
            # Buttons
            buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
            buttons.accepted.connect(dialog.accept)
            buttons.rejected.connect(dialog.reject)
            layout.addRow(buttons)
            
            dialog.setLayout(layout)
            
            # Show dialog and process result
            if dialog.exec() == QDialog.DialogCode.Accepted:
                try:
                    # Validate input
                    name = name_input.text().strip()
                    description = description_input.toPlainText().strip()
                    max_students = max_students_input.text().strip()
                    credits = credits_input.text().strip()
                    
                    if not all([name, description, max_students, credits]):
                        QMessageBox.warning(self, "Error", "Please fill in all required fields")
                        return
                    
                    try:
                        max_students = int(max_students)
                        credits = int(credits)
                    except ValueError:
                        QMessageBox.warning(self, "Error", "Max students and credits must be numbers")
                        return
                    
                    # Prepare course data
                    course_data = {
                        'name': name,
                        'description': description,
                        'teacher_id': teacher_id,
                        'max_students': max_students,
                        'credits': credits,
                        'is_active': True
                    }
                    
                    # Add course ID if provided
                    course_id = course_id_input.text().strip()
                    if course_id:
                        course_data['course_id'] = course_id
                    
                    print(f"[TeacherMainWindow] Creating course with data: {course_data}")
                    
                    # Create course
                    new_course = self.lms_system.course_manager.create_course(course_data)
                    
                    QMessageBox.information(self, "Success", f"Course '{new_course.name}' created successfully!")
                    print(f"[TeacherMainWindow] Course '{new_course.name}' created successfully")
                    
                    # Refresh course list
                    self.refresh_teacher_courses()
                    
                except Exception as e:
                    error_msg = f"Failed to create course: {str(e)}"
                    print(f"[TeacherMainWindow] Error: {error_msg}")
                    QMessageBox.critical(self, "Error", error_msg)

        def edit_teacher_course(self):
            """Edit teacher's course information"""
            print("[TeacherMainWindow] Starting to edit course...")
            
            if not self.lms_system or not self.lms_system.course_manager:
                error_msg = "System not initialized or course manager unavailable"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Get selected row
            selected_row = self.teacher_courses_table.currentRow()
            if selected_row < 0:
                print("[TeacherMainWindow] No course selected for editing")
                QMessageBox.warning(self, "Notice", "Please select a course to edit first")
                return
                
            # Get course ID
            course_id = self.teacher_courses_table.item(selected_row, 0).text()
            print(f"[TeacherMainWindow] Editing course ID: {course_id}")
            
            # Get course information
            course = self.lms_system.course_manager.get_course(course_id)
            if not course:
                error_msg = f"Course not found: {course_id}"
                print(f"[TeacherMainWindow] {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            print(f"[TeacherMainWindow] Found course: {course.name}")
            
            # Verify this course belongs to current teacher
            user_manager = self.lms_system.user_manager
            if not user_manager:
                error_msg = "User manager unavailable"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            current_teacher = user_manager.get_user_by_email(self.user_email)
            if not current_teacher:
                error_msg = "Current teacher user not found"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            if course.teacher_id != current_teacher.user_id:
                error_msg = "You can only edit your own courses"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Create edit course dialog
            dialog = QDialog(self)
            dialog.setWindowTitle("Edit Course")
            dialog.setMinimumWidth(400)
            
            layout = QFormLayout()
            
            # Input fields with current values
            name_input = QLineEdit(course.name)
            description_input = QTextEdit(course.description)
            max_students_input = QLineEdit(str(getattr(course, 'max_students', '30')))
            credits_input = QLineEdit(str(getattr(course, 'credits', '3')))
            status_checkbox = QCheckBox("Active")
            status_checkbox.setChecked(getattr(course, 'is_active', True))
            status_checkbox.setChecked(getattr(course, 'is_active', True))
            
            layout.addRow("Course Name:*", name_input)
            layout.addRow("Course Description:*", description_input)
            layout.addRow("Max Students:*", max_students_input)
            layout.addRow("Credits:*", credits_input)
            layout.addRow("Course Status:", status_checkbox)
            
            # Buttons
            buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
            buttons.accepted.connect(dialog.accept)
            buttons.rejected.connect(dialog.reject)
            layout.addRow(buttons)
            
            dialog.setLayout(layout)
            
            # Show dialog and process result
            if dialog.exec() == QDialog.DialogCode.Accepted:
                try:
                    # Validate input
                    name = name_input.text().strip()
                    description = description_input.toPlainText().strip()
                    max_students = max_students_input.text().strip()
                    credits = credits_input.text().strip()
                    
                    if not all([name, description, max_students, credits]):
                        QMessageBox.warning(self, "Error", "Please fill in all required fields")
                        return
                    
                    try:
                        max_students = int(max_students)
                        credits = int(credits)
                    except ValueError:
                        QMessageBox.warning(self, "Error", "Max students and credits must be numbers")
                        return
                    
                    # Update course data
                    update_data = {
                        'name': name,
                        'description': description,
                        'max_students': max_students,
                        'credits': credits,
                        'is_active': status_checkbox.isChecked()
                    }
                    
                    print(f"[TeacherMainWindow] Updating course data: {update_data}")
                    
                    # Update course
                    success = self.lms_system.course_manager.update_course(course_id, update_data)
                    
                    if success:
                        print(f"[TeacherMainWindow] Course '{course.name}' updated successfully")
                        QMessageBox.information(self, "Success", f"Course '{course.name}' updated successfully")
                        self.refresh_teacher_courses()  # Refresh course list
                    else:
                        print(f"[TeacherMainWindow] Failed to update course '{course.name}'")
                        QMessageBox.warning(self, "Failed", "Failed to update course")
                        
                except Exception as e:
                    error_msg = f"Failed to update course: {str(e)}"
                    print(f"[TeacherMainWindow] Error: {error_msg}")
                    QMessageBox.critical(self, "Error", error_msg)

        def view_teacher_course_students(self):
            """View students enrolled in selected course"""
            print("[TeacherMainWindow] Starting to view course students...")
            
            if not self.lms_system or not self.lms_system.course_manager:
                error_msg = "System not initialized or course manager unavailable"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Get selected row
            selected_row = self.teacher_courses_table.currentRow()
            if selected_row < 0:
                print("[TeacherMainWindow] No course selected for viewing students")
                QMessageBox.warning(self, "Notice", "Please select a course to view students first")
                return
                
            # Get course ID
            course_id = self.teacher_courses_table.item(selected_row, 0).text()
            course_name = self.teacher_courses_table.item(selected_row, 1).text()
            print(f"[TeacherMainWindow] Viewing students for course ID: {course_id}")
            
            # Get course information
            course = self.lms_system.course_manager.get_course(course_id)
            if not course:
                error_msg = f"Course not found: {course_id}"
                print(f"[TeacherMainWindow] {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Verify this course belongs to current teacher
            user_manager = self.lms_system.user_manager
            if not user_manager:
                error_msg = "User manager unavailable"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            current_teacher = user_manager.get_user_by_email(self.user_email)
            if not current_teacher:
                error_msg = "Current teacher user not found"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            if course.teacher_id != current_teacher.user_id:
                error_msg = "You can only view students in your own courses"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Get students in the course
            students = self.lms_system.course_manager.get_course_students(course_id)
            
            # Create students dialog
            dialog = QDialog(self)
            dialog.setWindowTitle(f"Students in {course_name}")
            dialog.resize(600, 400)
            
            layout = QVBoxLayout()
            
            # Students table
            students_table = QTableWidget()
            students_table.setColumnCount(4)
            students_table.setHorizontalHeaderLabels(["Student ID", "Name", "Email", "Enrollment Date"])
            students_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
            
            students_table.setRowCount(len(students))
            for row, student in enumerate(students):
                students_table.setItem(row, 0, QTableWidgetItem(student.user_id))
                students_table.setItem(row, 1, QTableWidgetItem(student.name))
                students_table.setItem(row, 2, QTableWidgetItem(student.email))
                students_table.setItem(row, 3, QTableWidgetItem(getattr(student, 'enrollment_date', 'N/A')))
            
            layout.addWidget(students_table)
            
            # Info label
            info_label = QLabel(f"Total students: {len(students)}")
            layout.addWidget(info_label)
            
            # Close button
            close_button = QPushButton("Close")
            close_button.clicked.connect(dialog.accept)
            layout.addWidget(close_button)
            
            dialog.setLayout(layout)
            dialog.exec()

        def refresh_teacher_assignments(self):
            """Refresh teacher's assignment list"""
            print(f"[TeacherMainWindow] Starting to refresh teacher's assignment list for teacher: {self.user_email}")
            
            if not self.lms_system or not self.lms_system.assignment_manager:
                error_msg = "System not initialized or assignment manager unavailable"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            try:
                # Get current teacher user
                user_manager = self.lms_system.user_manager
                if not user_manager:
                    error_msg = "User manager unavailable"
                    print(f"[TeacherMainWindow] Error: {error_msg}")
                    QMessageBox.warning(self, "Error", error_msg)
                    return
                    
                current_teacher = user_manager.get_user_by_email(self.user_email)
                if not current_teacher:
                    error_msg = "Current teacher user not found"
                    print(f"[TeacherMainWindow] Error: {error_msg}")
                    QMessageBox.warning(self, "Error", error_msg)
                    return
                
                teacher_id = current_teacher.user_id
                print(f"[TeacherMainWindow] Getting assignments for teacher ID: {teacher_id}")
                
                # Get teacher's courses first
                courses = self.lms_system.course_manager.get_teacher_courses(teacher_id)
                print(f"[TeacherMainWindow] Found {len(courses)} courses for teacher")
                
                # Get all assignments for these courses
                all_assignments = []
                for course in courses:
                    course_assignments = self.lms_system.assignment_manager.get_assignments_by_course(course.course_id)
                    all_assignments.extend(course_assignments)
                
                print(f"[TeacherMainWindow] Found {len(all_assignments)} assignments for teacher's courses")
                
                # Update table
                self.teacher_assignments_table.setRowCount(len(all_assignments))
                for row, assignment in enumerate(all_assignments):
                    self.teacher_assignments_table.setItem(row, 0, QTableWidgetItem(assignment.assignment_id))
                    self.teacher_assignments_table.setItem(row, 1, QTableWidgetItem(assignment.title))
                    
                    # Get course name
                    course = self.lms_system.course_manager.get_course(assignment.course_id)
                    course_name = course.name if course else "Unknown Course"
                    self.teacher_assignments_table.setItem(row, 2, QTableWidgetItem(course_name))
                    
                    # Format due date
                    due_date_str = assignment.due_date.strftime("%Y-%m-%d %H:%M")
                    self.teacher_assignments_table.setItem(row, 3, QTableWidgetItem(due_date_str))
                    
                    # Get submission count
                    submissions = self.lms_system.assignment_manager.get_submissions(assignment.assignment_id)
                    self.teacher_assignments_table.setItem(row, 4, QTableWidgetItem(str(len(submissions))))
                    
                self.statusBar().showMessage(f"Loaded {len(all_assignments)} assignments")
                print("[TeacherMainWindow] Teacher assignment list refreshed successfully")
                
            except Exception as e:
                error_msg = f"Failed to refresh teacher assignment list: {str(e)}"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                print(f"[TeacherMainWindow] Exception type: {type(e).__name__}")
                import traceback
                traceback.print_exc()
                QMessageBox.critical(self, "Error", error_msg)

        def create_teacher_assignment(self):
            """Create a new assignment"""
            print("[TeacherMainWindow] Starting to create new assignment...")
            
            if not self.lms_system or not self.lms_system.assignment_manager:
                error_msg = "System not initialized or assignment manager unavailable"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Get current teacher user
            user_manager = self.lms_system.user_manager
            if not user_manager:
                error_msg = "User manager unavailable"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            current_teacher = user_manager.get_user_by_email(self.user_email)
            if not current_teacher:
                error_msg = "Current teacher user not found"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            teacher_id = current_teacher.user_id
            
            # Get teacher's courses
            courses = self.lms_system.course_manager.get_teacher_courses(teacher_id)
            if not courses:
                error_msg = "You need to create a course first before creating assignments"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Create assignment dialog
            dialog = QDialog(self)
            dialog.setWindowTitle("Create Assignment")
            dialog.setMinimumWidth(500)
            
            layout = QFormLayout()
            
            # Course selection
            course_combo = QComboBox()
            for course in courses:
                course_combo.addItem(f"{course.name} ({course.course_id})", course.course_id)
            layout.addRow("Course:*", course_combo)
            
            # Assignment details
            title_input = QLineEdit()
            title_input.setPlaceholderText("Assignment title")
            layout.addRow("Title:*", title_input)
            
            description_input = QTextEdit()
            description_input.setPlaceholderText("Assignment description")
            description_input.setMaximumHeight(100)
            layout.addRow("Description:*", description_input)
            
            due_date_input = QLineEdit()
            due_date_input.setPlaceholderText("YYYY-MM-DD HH:MM")
            layout.addRow("Due Date:*", due_date_input)
            
            max_score_input = QLineEdit()
            max_score_input.setPlaceholderText("Maximum score")
            layout.addRow("Max Score:*", max_score_input)
            
            # Buttons
            button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
            button_box.accepted.connect(dialog.accept)
            button_box.rejected.connect(dialog.reject)
            layout.addRow(button_box)
            
            dialog.setLayout(layout)
            
            if dialog.exec() == QDialog.DialogCode.Accepted:
                try:
                    # Get form data
                    course_id = course_combo.currentData()
                    title = title_input.text().strip()
                    description = description_input.toPlainText().strip()
                    due_date_str = due_date_input.text().strip()
                    max_score = max_score_input.text().strip()
                    
                    # Validate input
                    if not all([title, description, due_date_str, max_score]):
                        error_msg = "Please fill in all required fields"
                        print(f"[TeacherMainWindow] Error: {error_msg}")
                        QMessageBox.warning(self, "Error", error_msg)
                        return
                        
                    # Parse max score
                    try:
                        max_score_float = float(max_score)
                        if max_score_float <= 0:
                            raise ValueError("Max score must be positive")
                    except ValueError as e:
                        error_msg = f"Invalid max score: {str(e)}"
                        print(f"[TeacherMainWindow] Error: {error_msg}")
                        QMessageBox.warning(self, "Error", error_msg)
                        return
                    
                    # Create assignment
                    assignment = self.lms_system.assignment_manager.create_assignment(
                        course_id=course_id,
                        title=title,
                        description=description,
                        due_date=due_date_str,
                        max_score=max_score_float,
                        created_by=teacher_id
                    )
                    
                    if assignment:
                        print(f"[TeacherMainWindow] Assignment '{title}' created successfully")
                        QMessageBox.information(self, "Success", f"Assignment '{title}' created successfully")
                        self.refresh_teacher_assignments()
                    else:
                        error_msg = "Failed to create assignment"
                        print(f"[TeacherMainWindow] Error: {error_msg}")
                        QMessageBox.warning(self, "Error", error_msg)
                        
                except Exception as e:
                    error_msg = f"Failed to create assignment: {str(e)}"
                    print(f"[TeacherMainWindow] Error: {error_msg}")
                    QMessageBox.critical(self, "Error", error_msg)

        def edit_teacher_assignment(self):
            """Edit selected assignment"""
            print("[TeacherMainWindow] Starting to edit assignment...")
            
            if not self.lms_system or not self.lms_system.assignment_manager:
                error_msg = "System not initialized or assignment manager unavailable"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Get selected row
            selected_row = self.teacher_assignments_table.currentRow()
            if selected_row < 0:
                print("[TeacherMainWindow] No assignment selected for editing")
                QMessageBox.warning(self, "Notice", "Please select an assignment to edit first")
                return
                
            # Get assignment ID
            assignment_id = self.teacher_assignments_table.item(selected_row, 0).text()
            print(f"[TeacherMainWindow] Editing assignment ID: {assignment_id}")
            
            # Get assignment
            assignment = self.lms_system.assignment_manager.get_assignment(assignment_id)
            if not assignment:
                error_msg = f"Assignment not found: {assignment_id}"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Verify this assignment belongs to current teacher
            user_manager = self.lms_system.user_manager
            if not user_manager:
                error_msg = "User manager unavailable"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            current_teacher = user_manager.get_user_by_email(self.user_email)
            if not current_teacher:
                error_msg = "Current teacher user not found"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Get course to verify ownership
            course = self.lms_system.course_manager.get_course(assignment.course_id)
            if not course or course.teacher_id != current_teacher.user_id:
                error_msg = "You can only edit assignments in your own courses"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Get teacher's courses
            courses = self.lms_system.course_manager.get_teacher_courses(current_teacher.user_id)
            
            # Create edit dialog
            dialog = QDialog(self)
            dialog.setWindowTitle("Edit Assignment")
            dialog.setMinimumWidth(500)
            
            layout = QFormLayout()
            
            # Course selection
            course_combo = QComboBox()
            current_index = 0
            for i, course in enumerate(courses):
                course_combo.addItem(f"{course.name} ({course.course_id})", course.course_id)
                if course.course_id == assignment.course_id:
                    current_index = i
            course_combo.setCurrentIndex(current_index)
            layout.addRow("Course:*", course_combo)
            
            # Assignment details
            title_input = QLineEdit()
            title_input.setText(assignment.title)
            layout.addRow("Title:*", title_input)
            
            description_input = QTextEdit()
            description_input.setText(assignment.description)
            description_input.setMaximumHeight(100)
            layout.addRow("Description:*", description_input)
            
            due_date_input = QLineEdit()
            due_date_input.setText(assignment.due_date.strftime("%Y-%m-%d %H:%M"))
            layout.addRow("Due Date:*", due_date_input)
            
            max_score_input = QLineEdit()
            max_score_input.setText(str(assignment.max_score))
            layout.addRow("Max Score:*", max_score_input)
            
            # Buttons
            button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
            button_box.accepted.connect(dialog.accept)
            button_box.rejected.connect(dialog.reject)
            layout.addRow(button_box)
            
            dialog.setLayout(layout)
            
            if dialog.exec() == QDialog.DialogCode.Accepted:
                try:
                    # Get form data
                    course_id = course_combo.currentData()
                    title = title_input.text().strip()
                    description = description_input.toPlainText().strip()
                    due_date_str = due_date_input.text().strip()
                    max_score = max_score_input.text().strip()
                    
                    # Validate input
                    if not all([title, description, due_date_str, max_score]):
                        error_msg = "Please fill in all required fields"
                        print(f"[TeacherMainWindow] Error: {error_msg}")
                        QMessageBox.warning(self, "Error", error_msg)
                        return
                        
                    # Parse max score
                    try:
                        max_score_float = float(max_score)
                        if max_score_float <= 0:
                            raise ValueError("Max score must be positive")
                    except ValueError as e:
                        error_msg = f"Invalid max score: {str(e)}"
                        print(f"[TeacherMainWindow] Error: {error_msg}")
                        QMessageBox.warning(self, "Error", error_msg)
                        return
                    
                    # Update assignment
                    assignment.title = title
                    assignment.description = description
                    assignment.due_date = due_date_str
                    assignment.max_score = max_score_float
                    assignment.course_id = course_id
                    
                    print(f"[TeacherMainWindow] Assignment '{title}' updated successfully")
                    QMessageBox.information(self, "Success", f"Assignment '{title}' updated successfully")
                    self.refresh_teacher_assignments()
                    
                except Exception as e:
                    error_msg = f"Failed to update assignment: {str(e)}"
                    print(f"[TeacherMainWindow] Error: {error_msg}")
                    QMessageBox.critical(self, "Error", error_msg)

        def view_teacher_submissions(self):
            """View submissions for selected assignment"""
            print("[TeacherMainWindow] Starting to view assignment submissions...")
            
            if not self.lms_system or not self.lms_system.assignment_manager:
                error_msg = "System not initialized or assignment manager unavailable"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Get selected row
            selected_row = self.teacher_assignments_table.currentRow()
            if selected_row < 0:
                print("[TeacherMainWindow] No assignment selected for viewing submissions")
                QMessageBox.warning(self, "Notice", "Please select an assignment to view submissions first")
                return
                
            # Get assignment ID
            assignment_id = self.teacher_assignments_table.item(selected_row, 0).text()
            assignment_name = self.teacher_assignments_table.item(selected_row, 1).text()
            print(f"[TeacherMainWindow] Viewing submissions for assignment ID: {assignment_id}")
            
            # Get assignment
            assignment = self.lms_system.assignment_manager.get_assignment(assignment_id)
            if not assignment:
                error_msg = f"Assignment not found: {assignment_id}"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Verify this assignment belongs to current teacher
            user_manager = self.lms_system.user_manager
            if not user_manager:
                error_msg = "User manager unavailable"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            current_teacher = user_manager.get_user_by_email(self.user_email)
            if not current_teacher:
                error_msg = "Current teacher user not found"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Get course to verify ownership
            course = self.lms_system.course_manager.get_course(assignment.course_id)
            if not course or course.teacher_id != current_teacher.user_id:
                error_msg = "You can only view submissions for assignments in your own courses"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Get submissions
            submissions = self.lms_system.assignment_manager.get_submissions(assignment_id)
            
            # Create submissions dialog
            dialog = QDialog(self)
            dialog.setWindowTitle(f"Submissions for {assignment_name}")
            dialog.resize(800, 500)
            
            layout = QVBoxLayout()
            
            # Submissions table
            submissions_table = QTableWidget()
            submissions_table.setColumnCount(6)
            submissions_table.setHorizontalHeaderLabels(["Student ID", "Student Name", "Submission Time", "Status", "Score", "Graded"])
            submissions_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
            
            submissions_table.setRowCount(len(submissions))
            for row, submission in enumerate(submissions):
                # Get student info
                student = user_manager.get_user(submission.student_id)
                student_name = student.name if student else "Unknown Student"
                
                submissions_table.setItem(row, 0, QTableWidgetItem(submission.student_id))
                submissions_table.setItem(row, 1, QTableWidgetItem(student_name))
                submissions_table.setItem(row, 2, QTableWidgetItem(submission.submitted_at.strftime("%Y-%m-%d %H:%M")))
                
                # Status
                status = "Late" if submission.is_late else "On Time"
                submissions_table.setItem(row, 3, QTableWidgetItem(status))
                
                # Score and graded status
                if hasattr(submission, 'grade') and submission.grade is not None:
                    submissions_table.setItem(row, 4, QTableWidgetItem(str(submission.grade) if submission.grade is not None else "Not graded"))
                    submissions_table.setItem(row, 5, QTableWidgetItem("Yes"))
                else:
                    submissions_table.setItem(row, 4, QTableWidgetItem("-"))
                    submissions_table.setItem(row, 5, QTableWidgetItem("No"))
                
            layout.addWidget(submissions_table)
            
            # Info label
            info_label = QLabel(f"Total submissions: {len(submissions)}")
            layout.addWidget(info_label)
            
            # Close button
            close_button = QPushButton("Close")
            close_button.clicked.connect(dialog.accept)
            layout.addWidget(close_button)
            
            dialog.setLayout(layout)
            dialog.exec()

        def refresh_grading(self):
            """Refresh grading table"""
            print(f"[TeacherMainWindow] Starting to refresh grading table for teacher: {self.user_email}")
            
            if not self.lms_system or not self.lms_system.assignment_manager:
                error_msg = "System not initialized or assignment manager unavailable"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            try:
                # Get current teacher user
                user_manager = self.lms_system.user_manager
                if not user_manager:
                    error_msg = "User manager unavailable"
                    print(f"[TeacherMainWindow] Error: {error_msg}")
                    QMessageBox.warning(self, "Error", error_msg)
                    return
                    
                current_teacher = user_manager.get_user_by_email(self.user_email)
                if not current_teacher:
                    error_msg = "Current teacher user not found"
                    print(f"[TeacherMainWindow] Error: {error_msg}")
                    QMessageBox.warning(self, "Error", error_msg)
                    return
                
                teacher_id = current_teacher.user_id
                
                # Get teacher's courses
                courses = self.lms_system.course_manager.get_teacher_courses(teacher_id)
                
                # Get all submissions for these courses
                all_submissions = []
                for course in courses:
                    course_assignments = self.lms_system.assignment_manager.get_assignments_by_course(course.course_id)
                    for assignment in course_assignments:
                        submissions = self.lms_system.assignment_manager.get_submissions(assignment.assignment_id)
                        for submission in submissions:
                            all_submissions.append({
                                'submission': submission,
                                'assignment': assignment,
                                'course': course
                            })
                
                print(f"[TeacherMainWindow] Found {len(all_submissions)} submissions for grading")
                
                # Update table
                self.grading_table.setRowCount(len(all_submissions))
                for row, submission_data in enumerate(all_submissions):
                    submission = submission_data['submission']
                    assignment = submission_data['assignment']
                    course = submission_data['course']
                    
                    # Get student info
                    student = user_manager.get_user(submission.student_id)
                    student_name = student.name if student else "Unknown Student"
                    
                    self.grading_table.setItem(row, 0, QTableWidgetItem(student_name))
                    self.grading_table.setItem(row, 1, QTableWidgetItem(course.name))
                    self.grading_table.setItem(row, 2, QTableWidgetItem(assignment.title))
                    
                    # Status
                    status = "Late" if submission.is_late else "On Time"
                    self.grading_table.setItem(row, 3, QTableWidgetItem(status))
                    
                    # Score
                    if hasattr(submission, 'grade') and submission.grade is not None:
                        self.grading_table.setItem(row, 4, QTableWidgetItem(str(submission.grade) if submission.grade is not None else "Not graded"))
                    else:
                        self.grading_table.setItem(row, 4, QTableWidgetItem("Not graded"))
                    
                    # Action button
                    grade_button = QPushButton("Grade")
                    grade_button.clicked.connect(lambda checked, s=submission: self.grade_submission(s))
                    self.grading_table.setCellWidget(row, 5, grade_button)
                    
                self.statusBar().showMessage(f"Loaded {len(all_submissions)} submissions for grading")
                print("[TeacherMainWindow] Grading table refreshed successfully")
                
            except Exception as e:
                error_msg = f"Failed to refresh grading table: {str(e)}"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                print(f"[TeacherMainWindow] Exception type: {type(e).__name__}")
                import traceback
                traceback.print_exc()
                QMessageBox.critical(self, "Error", error_msg)

        def grade_assignment(self):
            """Grade selected assignment"""
            print("[TeacherMainWindow] Starting to grade assignment...")
            
            # Get selected row
            selected_row = self.grading_table.currentRow()
            if selected_row < 0:
                print("[TeacherMainWindow] No submission selected for grading")
                QMessageBox.warning(self, "Notice", "Please select a submission to grade first")
                return
                
            # Get submission from table data (stored in user data)
            grade_button = self.grading_table.cellWidget(selected_row, 5)
            if grade_button:
                grade_button.click()

        def grade_submission(self, submission):
            """Grade a specific submission"""
            print(f"[TeacherMainWindow] Starting to grade submission: {submission.submission_id}")
            
            if not self.lms_system or not self.lms_system.assignment_manager:
                error_msg = "System not initialized or assignment manager unavailable"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Get assignment
            assignment = self.lms_system.assignment_manager.get_assignment(submission.assignment_id)
            if not assignment:
                error_msg = f"Assignment not found: {submission.assignment_id}"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            # Get student info
            user_manager = self.lms_system.user_manager
            student = user_manager.get_user(submission.student_id)
            student_name = student.name if student else "Unknown Student"
            
            # Create grading dialog
            dialog = QDialog(self)
            dialog.setWindowTitle(f"Grade Submission - {student_name}")
            dialog.setMinimumWidth(500)
            
            layout = QFormLayout()
            
            # Assignment info
            layout.addRow("Assignment:", QLabel(assignment.title))
            layout.addRow("Student:", QLabel(student_name))
            layout.addRow("Submission Time:", QLabel(submission.submitted_at.strftime("%Y-%m-%d %H:%M")))
            layout.addRow("Status:", QLabel("Late" if submission.is_late else "On Time"))
            
            # Submission content
            content_label = QLabel(str(submission.content))
            content_label.setWordWrap(True)
            content_label.setMaximumHeight(100)
            layout.addRow("Submission Content:", content_label)
            
            # Grade input
            score_input = QLineEdit()
            score_input.setPlaceholderText(f"Score (0-{assignment.max_score})")
            if hasattr(submission, 'grade') and submission.grade is not None:
                score_input.setText(str(submission.grade) if submission.grade is not None else "")
            layout.addRow("Score:*", score_input)
            
            # Feedback input
            feedback_input = QTextEdit()
            feedback_input.setPlaceholderText("Feedback for student")
            feedback_input.setMaximumHeight(100)
            if hasattr(submission, 'feedback') and submission.feedback is not None:
                feedback_input.setText(submission.feedback)
            layout.addRow("Feedback:", feedback_input)
            
            # Buttons
            button_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
            button_box.accepted.connect(dialog.accept)
            button_box.rejected.connect(dialog.reject)
            layout.addRow(button_box)
            
            dialog.setLayout(layout)
            
            if dialog.exec() == QDialog.DialogCode.Accepted:
                try:
                    # Get form data
                    score_str = score_input.text().strip()
                    feedback = feedback_input.toPlainText().strip()
                    
                    # Validate score
                    if not score_str:
                        error_msg = "Please enter a score"
                        print(f"[TeacherMainWindow] Error: {error_msg}")
                        QMessageBox.warning(self, "Error", error_msg)
                        return
                        
                    try:
                        score = float(score_str)
                        if score < 0 or score > assignment.max_score:
                            raise ValueError(f"Score must be between 0 and {assignment.max_score}")
                    except ValueError as e:
                        error_msg = f"Invalid score: {str(e)}"
                        print(f"[TeacherMainWindow] Error: {error_msg}")
                        QMessageBox.warning(self, "Error", error_msg)
                        return
                    
                    # Get current teacher ID for grading
                    current_teacher = user_manager.get_user_by_email(self.user_email)
                    grader_id = current_teacher.user_id if current_teacher else None
                    
                    # Grade submission
                    grade = self.lms_system.assignment_manager.grade_submission(
                        submission.submission_id,
                        grader_id,
                        score,
                        feedback if feedback else None
                    )
                    
                    if grade:
                        print(f"[TeacherMainWindow] Submission graded successfully with score: {score}")
                        QMessageBox.information(self, "Success", f"Submission graded successfully with score: {score}")
                        self.refresh_grading()
                    else:
                        error_msg = "Failed to grade submission"
                        print(f"[TeacherMainWindow] Error: {error_msg}")
                        QMessageBox.warning(self, "Error", error_msg)
                        
                except Exception as e:
                    error_msg = f"Failed to grade submission: {str(e)}"
                    print(f"[TeacherMainWindow] Error: {error_msg}")
                    QMessageBox.critical(self, "Error", error_msg)

        def export_grades(self):
            """Export grades to file"""
            print("[TeacherMainWindow] Starting to export grades...")
            
            if not self.lms_system or not self.lms_system.assignment_manager:
                error_msg = "System not initialized or assignment manager unavailable"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.warning(self, "Error", error_msg)
                return
                
            try:
                from PyQt6.QtWidgets import QFileDialog
                
                # Get save file path
                file_path, _ = QFileDialog.getSaveFileName(
                    self,
                    "Export Grades",
                    "grades.csv",
                    "CSV Files (*.csv);;All Files (*)"
                )
                
                if not file_path:
                    return
                    
                # Get current teacher user
                user_manager = self.lms_system.user_manager
                current_teacher = user_manager.get_user_by_email(self.user_email)
                teacher_id = current_teacher.user_id
                
                # Get teacher's courses
                courses = self.lms_system.course_manager.get_teacher_courses(teacher_id)
                
                # Create CSV content
                csv_content = "Course,Assignment,Student,Score,Feedback,Submission Time,Status\n"
                
                for course in courses:
                    course_assignments = self.lms_system.assignment_manager.get_assignments_by_course(course.course_id)
                    for assignment in course_assignments:
                        submissions = self.lms_system.assignment_manager.get_submissions(assignment.assignment_id)
                        for submission in submissions:
                            student = user_manager.get_user(submission.student_id)
                            student_name = student.name if student else "Unknown Student"
                            
                            score = "-"
                            feedback = "-"
                            if hasattr(submission, 'grade') and submission.grade is not None:
                                score = str(submission.grade)
                                if hasattr(submission, 'feedback') and submission.feedback is not None:
                                    feedback = submission.feedback.replace(",", ";")  # Replace commas for CSV
                            
                            status = "Late" if submission.is_late else "On Time"
                            
                            csv_content += f'"{course.name}","{assignment.title}","{student_name}",{score},"{feedback}","{submission.submitted_at.strftime("%Y-%m-%d %H:%M")}","{status}"\n'
                
                # Write to file
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(csv_content)
                
                print(f"[TeacherMainWindow] Grades exported successfully to: {file_path}")
                QMessageBox.information(self, "Success", f"Grades exported successfully to:\n{file_path}")
                
            except Exception as e:
                error_msg = f"Failed to export grades: {str(e)}"
                print(f"[TeacherMainWindow] Error: {error_msg}")
                QMessageBox.critical(self, "Error", error_msg)

    class GUI:
            """GUI main class"""

            def __init__(self, lms_system=None):
                self.lms_system = lms_system
                self.app: Optional[QApplication] = None
                self.login_window: Optional[LoginWindow] = None
                self.main_window: Optional[MainWindow] = None
                
                # Set up exception handling
                sys.excepthook = self.exception_hook

            def exception_hook(self, exc_type, exc_value, exc_traceback):
                """Global exception handling hook"""
                print(f"\n=== GUI Exception Caught ===")
                print(f"Exception Type: {exc_type.__name__}")
                print(f"Exception Info: {exc_value}")
                print(f"Exception Location:")
                import traceback
                traceback.print_tb(exc_traceback)
                print("=" * 50)
                
                # Show error dialog
                error_msg = f"An error occurred:\n{exc_type.__name__}: {exc_value}"
                QMessageBox.critical(None, "System Error", error_msg)

            def start(self):
                """Start GUI application"""
                print("[GUI] Starting GUI application...")
                
                if not PYQT6_AVAILABLE:
                    print("[GUI] Error: PyQt6 unavailable, cannot start GUI interface")
                    return False

                try:
                    print("[GUI] Creating QApplication instance...")
                    # Create application
                    self.app = QApplication(sys.argv)
                    
                    print("[GUI] Creating login window...")
                    # Create login window
                    self.login_window = LoginWindow(self.lms_system)
                    self.login_window.login_successful.connect(self.on_login_successful)
                    self.login_window.show()
                    
                    print("[GUI] GUI application started successfully, entering event loop")
                    
                    # Run application
                    result = self.app.exec() == 0
                    print(f"[GUI] GUI application event loop ended, return value: {result}")
                    return result
                    
                except Exception as e:
                    print(f"[GUI] Error starting GUI application: {type(e).__name__}: {e}")
                    import traceback
                    traceback.print_exc()
                    return False

            def on_login_successful(self, email: str, password: str):
                """Handle login successful event"""
                print(f"[GUI] Login request: user {email}")
                
                try:
                    # Verify user login
                    if self.lms_system:
                        print(f"[GUI] Verifying user credentials...")
                        if self.lms_system.auth_system.login(email, password):
                            user = self.lms_system.auth_system.current_user
                            user_type = type(user).__name__
                            print(f"[GUI] User {email} login successful, user type: {user_type}")
                            
                            # Close login window
                            if self.login_window:
                                self.login_window.close()

                            # Create different main windows based on user type
                            if user_type == "Admin":
                                print("[GUI] Creating admin main window...")
                                self.main_window = AdminMainWindow(email, user, self.lms_system)
                            elif user_type == "Teacher":
                                print("[GUI] Creating teacher main window...")
                                self.main_window = TeacherMainWindow(email, user, self.lms_system)
                            else:  # Student or default
                                print("[GUI] Creating student main window...")
                                self.main_window = StudentMainWindow(email, user, self.lms_system)
                            
                            # Set parent_gui reference for logout to return to login screen
                            self.main_window.parent_gui = self
                            self.main_window.show()
                            print("[GUI] Main window displayed successfully")
                        else:
                            print(f"[GUI] User {email} login failed: incorrect username or password")
                            QMessageBox.warning(None, "Login Failed", "Incorrect username or password")
                    else:
                        print("[GUI] Error: LMSSystem not initialized")
                        QMessageBox.critical(None, "System Error", "System not properly initialized")
                        
                except Exception as e:
                    print(f"[GUI] Error during login processing: {type(e).__name__}: {e}")
                    import traceback
                    traceback.print_exc()
                    QMessageBox.critical(None, "Login Error", f"Error during login process:\n{e}")

            def show_login_window(self):
                """Display login window (for logout)"""
                try:
                    print("[GUI] Redisplaying login window...")
                    
                    # Clean up main window
                    if self.main_window:
                        self.main_window = None
                    
                    # Create new login window
                    self.login_window = LoginWindow(self.lms_system)
                    self.login_window.login_successful.connect(self.on_login_successful)
                    self.login_window.show()
                    
                    print("[GUI] Login window redisplayed")
                    
                except Exception as e:
                    print(f"[GUI] Error redisplaying login window: {type(e).__name__}: {e}")
                    import traceback
                    traceback.print_exc()

else:
    class GUI:
        """GUI main class (placeholder when PyQt6 is unavailable)"""

        def __init__(self, lms_system=None):
            self.lms_system = lms_system

        def start(self):
            """Start GUI application (placeholder)"""
            print("PyQt6 unavailable, cannot start GUI interface")
            return False

# Example usage
if __name__ == "__main__":
    gui = GUI()
    gui.start()